Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework - SearchFilter not filtering

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.

like image 771
Oz Bar-Shalom Avatar asked Dec 17 '16 22:12

Oz Bar-Shalom


2 Answers

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

like image 188
serg Avatar answered Nov 09 '22 13:11

serg


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.

like image 33
Paul Tuckett Avatar answered Nov 09 '22 13:11

Paul Tuckett