Home » Django & REST Api » Implementing filtering against query parameters for viewsets in DRF

Implementing filtering against query parameters for viewsets in DRF

This post is related to / in continuation with “Writing class based Views in Django REST Framework” , you can also find all related articles at “Django and Django-REST Framework” page.

You may also read “Why filters are required in Django REST Framework ?” if you are need to know in which situations filters will be helpful.

In this post we will show how to get started with implementation of filters with Django REST Framework. Specific to this post, we will demo filtering with viewsets.

Before you start the server, make sure django-filters are installed as,

pip install django-filter

change helloproject/settings.py as,

INSTALLED_APPS = [
    'django_filters',
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}

As above, The default filter backends is set globally, using the DEFAULT_FILTER_BACKENDS setting.

Change your app’s views.py from, ( helloproject/helloapp/views.py )

class UserInfoView(viewsets.ModelViewSet) :
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer

to add filter_fields for the fields from modal which you want to search with,

class UserInfoView(viewsets.ModelViewSet) :
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    filter_fields = ["username"]

If you don’t want to add global filter backend, you can set it per view by removing from settings.py and add it per view using “filter_backends = [django_filters.rest_framework.DjangoFilterBackend]” in views.py as,

class UserInfoView(viewsets.ModelViewSet) :
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
    filter_fields = ["username"]

Now, lets say we want to search JSON object with username as lynxbee3 then we just need to call user API with “?username=lynxbee3” as, “http://192.168.0.106:8001/users/?username=lynxbee3” where, “username” is the filter and “lynxbee3” is search string, which you can search any object.

You can find all the code at https://github.com/lynxbee/drf_api_class_based_views.git

Reference : https://www.django-rest-framework.org/api-guide/filtering/


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment