How to Use DjangoFilterBackend in Django REST framework

DjangoFilterBackend is a powerful tool for filtering data in Django REST framework. It allows you to easily filter data based on various criteria, such as date ranges, text searches, and more. In this tutorial, we will show you how to use DjangoFilterBackend in Django REST framework.

Install DjangoFilterBackend

The first step is to install DjangoFilterBackend. To do this, open a terminal window and run the following command:

pip install django-filter

This will install the latest version of DjangoFilterBackend. Once the installation is complete, you can move on to the next step.

Add DjangoFilterBackend to Your Settings

Once DjangoFilterBackend is installed, you need to add it to your settings. To do this, open the settings.py file and add the following line:

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

This will enable DjangoFilterBackend in your Django REST framework.

Create a FilterSet

The next step is to create a FilterSet. A FilterSet is a class that contains the filters you want to use. To create a FilterSet, create a new file called filters.py and add the following code:

import django_filters class MyFilterSet(django_filters.FilterSet): start_date = django_filters.DateFilter(name='date', lookup_expr='gte') end_date = django_filters.DateFilter(name='date', lookup_expr='lte') min_price = django_filters.NumberFilter(name='price', lookup_expr='gte') max_price = django_filters.NumberFilter(name='price', lookup_expr='lte')

This FilterSet contains four filters: start_date, end_date, min_price, and max_price. You can add more filters as needed.

Add the FilterSet to Your View

Once you have created the FilterSet, you need to add it to your view. To do this, open the view.py file and add the following line:

filter_class = MyFilterSet

This will enable the FilterSet in your view.

Test the Filter

The final step is to test the filter. To do this, open a terminal window and run the following command:

python manage.py test

This will run the tests for the filter. If the tests pass, then the filter is working correctly.

Conclusion

In this tutorial, we have shown you how to use DjangoFilterBackend in Django REST framework. We have shown you how to install DjangoFilterBackend, add it to your settings, create a FilterSet, add the FilterSet to your view, and test the filter. We hope you have found this tutorial helpful.

Useful Links