2

I have a ModelViewSet with SearchFilter and OrderingFilter. Everything works fine, but when I try to filter by one specific field (like localhost:8000:/es/countries/?code=MX), it returns all records even when only one matches the criteria. When I use a generic search, like localhost:8000:/es/countries/?search=MX, it works fine.

This is my ViewSet:

class CountryViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = models.Country.objects.all()
    serializer_class = serializers.CountrySerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('name', 'code', 'calling_code')
    filter_fields = ('name', 'code', 'calling_code')

1 Answer 1

3

You can use the DjangoFilterBakend.

In your code you are using search_fields, it only works with search param. (as it is for searching and for filtering!!)

You need to add DjangoFilterBackend same as you have added SearchFilter and OrderingFilter in filter_backends field. And then mention the filter that you want in filter_fields field.

For eg:

class CountryViewSet(viewsets.ModelViewSet):
   permission_classes = (permissions.IsAuthenticated,)
   queryset = models.Country.objects.all()
   serializer_class = serializers.CountrySerializer
   filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend)
   search_fields = ('name', 'code', 'calling_code')
   filter_fields = ('name', 'code', 'calling_code')

You will also have to install django-filter.

pip install django-filter

Finally add django_filter to INSTALLED_APPS.

INSTALLED_APPS = [
    ....
    'django_filters',
]
Sign up to request clarification or add additional context in comments.

2 Comments

I followed your suggestion, but I got this error: django.template.exceptions.TemplateDoesNotExist: django_filters/rest_framework/form.html. Thanks for your help
Add django_filters as INSTALLED_APPS for template rendering

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.