[Django]-How to add search parameters to GET request in Django REST Framework?

7👍

✅

Search parameters are called filter parameters in terms of django-rest-framework. There are many ways to apply the filtering, check the documentation.

In most cases, you need to override just view, not serializer or any other module.

One obvious approach to do it, is to override view’s queryset. Example:

# access to /api/foo/?category=animal

class FooListView(generics.ListAPIView):
    model = Foo
    serializer_class = FooSerializer

    def get_queryset(self):
        qs = super(FooListView, self).get_queryset()
        category = self.request.query_params.get("category", None)
        if category:
            qs = qs.filter(category=category)
        return qs

But, django-rest-framework allows to do such things automatically, using django-filter.

Install it first:

pip install django-filter

Then specify in your view, by what fields you want to filter:

class FooListView(generics.ListAPIView):
    model = Foo
    serializer_class = FooSerializer
    filter_fields = ('category', )

This will do the same, as in previous example, but less code used.

There are many ways to customize this filtering, look here and here for details.

There is also a way to apply filtering globally:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}

Leave a comment