How to use regular filter with SearchFilter in Django Rest Framework?

I am using DRF (Django Rest Framework).

I declared a ModelViewSet and now I want to add filters to it.

class GoodsViewSet(viewsets.ModelViewSet): class Filter(FilterSet): class Meta: model = m.Goods filter_class = Filter filter_backends = (SearchFilter, Filter) search_fields = ['name',] queryset = m.Goods.objects.all() serializer_class = s.GoodsSerializer 

Seeing that I declared a subclass of the Filter class and applied it with:

 filter_class = Filter 

It worked at the beginning before adding lines:

 filter_backends = (SearchFilter, Filter) search_fields = ['name',] 

This was stated by the document .

And now the search filter is applied when the normal filter_class skipped.

In a word, they cannot work together.

How to get around this?

+6
source share
1 answer

Finally, I found that we should specify two filter_backends together:

 from rest_framework.filters import SearchFilter from django_filters.rest_framework import DjangoFilterBackend class GoodsViewSet(viewsets.ModelViewSet): class Filter(FilterSet): class Meta: model = m.Goods filter_class = Filter filter_backends = (SearchFilter, DjangoFilterBackend) search_fields = ['name',] queryset = m.Goods.objects.all() serializer_class = s.GoodsSerializer 

Or we can ignore the filter_backends field in a specific ViewSet class, but apply them globally in settings.py :

 REST_FRAMEWORK = { # ... other configurations 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.SearchFilter', 'django_filters.rest_framework.DjangoFilterBackend', ), } 

So the filter_class and search_fields options are available simultaneously on the ViewSet.

+12
source

Source: https://habr.com/ru/post/1012021/


All Articles