Filtering a ModelViewSet

2,159 views
Skip to first unread message

Joe Borg

unread,
Apr 1, 2015, 5:25:15 AM4/1/15
to django-res...@googlegroups.com
I'm trying to add filtering capability in a User object ViewSet.

Here's my code:

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer

I'd like to be able to filter from the URL - e.g. ./users?username=joe

I've been reading http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-url but that's an example for a ListAPIView, rather than a ModelViewSet, so I get exceptions when I try to add the filtering in.

Obviously, I can do

queryset = User.objects.filter(username='joe')

and it works, but I want to be able to do this from the URL (as well as retain the PK retrieval).

Thanks,
Joe

Joe Borg

unread,
Apr 1, 2015, 5:50:38 AM4/1/15
to django-res...@googlegroups.com

Joseph Wayodi

unread,
Apr 1, 2015, 6:28:16 AM4/1/15
to django-res...@googlegroups.com
You can use DjangoFilterBackend [1], and then set the fields to filter
by in your viewset's "filter_fields" property:

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ('username',)

[1] <http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend>

Joseph.

Joseph Wayodi

unread,
Apr 1, 2015, 6:31:36 AM4/1/15
to django-res...@googlegroups.com
Oops!
Reply all
Reply to author
Forward
0 new messages