Django REST framework - SearchFilter not filtering

13.4k views Asked by At

I am using Django 1.10 and django-rest-framework 3.5.3. I would like to have a generic search query: search for a value on many fields. I Found the SearchFilter on the Docs.

I tried to add the filter backend to the ViewSet, but it seems not to be working. Any search query response with all the objects.

ViewSet:

from rest_framework import filters

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_backends = (filters.SearchFilter,)
    filter_fields = ['username', 'email', 'is_staff', 'groups']

Query url:

http://localhost:8000/users/?search=something

In addition, at the docs they show that a new button "Filter" added to the django rest web page. It does not in my case.

2

There are 2 answers

0
serg On BEST ANSWER

Instead of filter_fields use search_fields. filter_fields is for enabling filtering on specific fields, like /users/?username=something&is_staff=True.

2
Paul Tuckett On

In response to your second issue and as an FYI, if you add SearchFilter to your filter_backends attribute, you have to add a search_fields attribute, and vise versa. Same goes for DjangoFilterBackend, you have to add a filter_fields attribute. Without them, the "Filter" button on the browsable api will not be available.