Skip to content Skip to sidebar Skip to footer

Filtering In Django Rest Framework

In my project I use django rest framework. To filter the results I use django_filters backend. There is my code: models.py from django.db import models class Region(models.Model)

Solution 1:

There are a few options, but the easiest way is to just override 'get_queryset' in your API view.

Example from the docs adapted to your use case:

classTownList(generics.ListAPIView):
    queryset = Town.objects.all()
    serializer_class = TownSerializer
    filter_class = TownFilter(generics.ListAPIView)
    serializer_class = PurchaseSerializer

    defget_queryset(self):
        queryset = Town.objects.all()
        search_param = self.request.QUERY_PARAMS.get('search', None)
        if search_param isnotNone:
            """
            set queryset here or use your TownFilter 
            """return queryset

Another way is to set your search_fields on the list api view class in combination use the SearchFilter class. The problem is that if you're filtering over multiple models, you may have to do some additional implementation here to make sure it's looking at exactly what you want. If you're not doing anything fancy, just put double underscores for region for example: region__name

Post a Comment for "Filtering In Django Rest Framework"