Filter data in Django Rest Framework
Last Updated :
30 May, 2021
Django REST Framework’s generic list view, by default, returns the entire query sets for a model manager. For real-world applications, it is necessary to filter the queryset to retrieve the relevant results based on the need. So, let’s discuss how to create a RESTful Web Service that provides filtering capabilities.
- DjangoFilterBackend
- SearchFilter
- OrderingFilter
Note: You can refer The Browsable API section for Models, Serializers, and Views of Project used in the article
DjangoFilterBackend
The DjangoFilterBackend class is used to filter the queryset based on a specified set of fields. This backend class automatically creates a FilterSet (django_filters.rest_framework.FilterSet) class for the given fields. We can also create our own FilterSet class with customized settings.
To configure filter backend classes in our Django Web Service, we need to install the django-filter package in our virtual environment. Make sure you quit the Django development server (Ctrl + C) and activate the virtual environment. Let’s run the below command.
pip install django-filter
After installation, we need to define the django_filters application to INSTALLED_APPS in the settings.py file.
Python3
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
'robots.apps.RobotsConfig' ,
'django_filters' ,
]
|
As a next step, we need to set the DjangoFilterBackend class from django_filters as the default filter class. Let’s mention it to the REST_FRAMEWORK dictionary in the settings.py file.
Python3
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS' 🙁
'django_filters.rest_framework.DjangoFilterBackend' ,
),
}
|
Now our RESTful web service is configured to make use of the filtering feature provided by django_filters.rest_framework.DjangoFilterBackend class. Let’s filter the robot class that retrieves a list of robots. The RobotList class as follows:
Python3
class RobotList(generics.ListCreateAPIView):
queryset = Robot.objects. all ()
serializer_class = RobotSerializer
name = 'robot-list'
filter_fields = (
'robot_category' ,
'manufacturer' ,
)
|
Here, you can notice an attribute named filter_fileds where we specify the field name to filter against. Now, we can retrieve robots based on their category (robot_category) and/or manufacturer.
Let’s filter the robots based on the robot category. The HTTPie command is
http “:8000/robot/?robot_category=2”
Output:

Let’s try another HTTPie command that filters robots based on robot category and manufacturer. The HTTPie command is
http “:8000/robot/?robot_category=2&manufacturer=1”
Output:

Now let’s check the functionality in Browsable API. You can browse the below URL
http://127.0.0.1:8000/robot/

You can click the Filters button in the top right corner to make use of the filter feature. It will display as shown below

On clicking the submit button you will get the result based on the populated filter fields as shown below.

SearchFilter
The SearchFilter class supports a single query parameter-based searching feature, and it is based on the Django admin’s search function.
By default, SearchFilter class uses case-insensitive partial matches, and it may contain multiple search terms (should be whitespace and/or comma-separated). We can also restrict the search behavior by prepending various characters to the search_fields.
- ‘^’ Starts-with search.
- ‘=’ Exact matches.
- ‘@’ Full-text search. ( for Django’s PostgreSQL backend)
- ‘$’ Regex search
By default, the search parameter is named search, and you can override it with the SEARCH_PARAM setting. Let’s make use of SearchFilter class by adding the rest_framework.filters.SearchFilter class to the REST_FRAMEWORK dictionary.
Python3
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS' 🙁
'django_filters.rest_framework.DjangoFilterBackend' ,
'rest_framework.filters.SearchFilter' ,
),
}
|
Our RobotList class looks as follows:
Python3
class RobotList(generics.ListCreateAPIView):
queryset = Robot.objects. all ()
serializer_class = RobotSerializer
name = 'robot-list'
search_fields = (
'^name' ,
)
|
The search_fields attribute specifies a tuple of strings, which indicates the field names that we want to include in the search feature.
Let’s search the robots, which starts with the name ‘IRB’. The HTTPie command is
http “:8000/robot/?search=IRB”
Output:

OrderingFilter
The OrderingFilter class allows you to order the result based on the specified fields. By default, the query parameter is named ordering, and it can be overridden with the ORDERING_PARAM setting. The ordering_field attribute specifies a tuple of strings, which indicates the field names to sort the results.
If you don’t specify an ordering_fields attribute on the view, the filter class allows the user to filter on any readable fields specified by the serializer_class attribute. This permits the user to order against sensitive information such as password hash fields and so on, which may lead to unexpected data leakage. You can also specify a default order by setting an ordering attribute on the view. It can be either a string or a list/tuple of strings.
To make use of OrderingFilter class, we need to set the class as the default ordering filter class to the REST_FRAMEWORK dictionary.
Python3
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS' 🙁
'django_filters.rest_framework.DjangoFilterBackend' ,
'rest_framework.filters.OrderingFilter' ,
),
}
|
Let’s mention the ordering_fields attribute on the RobotList class. The code as follows:
Python3
class RobotList(generics.ListCreateAPIView):
queryset = Robot.objects. all ()
serializer_class = RobotSerializer
name = 'robot-list'
ordering_fields = (
'price' ,
)
|
Now, let’s retrieve robots based on the increase in price order. The HTTPie command is
http “:8000/robot/?ordering=price”
Output:

Similar Reads
Customizing Filters in Django REST Framework
Prerequisite: Adding Filtering in APIs â Django REST Framework [link needed article on published yet] Django filters facilitate filtering the queryset to retrieve the relevant results based on the values assigned to the filter fields. But, what if the user wants to retrieve details within a given ra
4 min read
Browsable API in Django REST Framework
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use we
8 min read
How To Filter A Nested Serializer In Django Rest Framework?
When building APIs with Django Rest Framework (DRF), nested serializers are commonly used to represent relationships between models. A nested serializer allows us to include data from related models within a serializer. However, there are instances where we might want to filter the data returned by
6 min read
Django REST Framework Installation
Django REST Framework can be installed via pip package similar to Django installation. Since Django REST Framework is a wrapper over default Django Framework, to install it, Django should be installed already. Now to install rest framework follow the below process. Prerequisites Python Pip Django Ho
1 min read
Model Fieldname restrictions in Django Framework
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating or
2 min read
Search Data in Django From Firebase
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud st
4 min read
URL fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
5 min read
Initial form data - Django Forms
After creating a Django Form, if one requires some or all fields of the form be filled with some initial data, one can use functionality of Django forms to do so. It is not the same as a placeholder, but this data will be passed into the view when submitted. There are multiple methods to do this, mo
3 min read
Function based Views - Django Rest Framework
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator. Before
13 min read
7 Best Frontend Framework for Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django is one of the most popular framework for building robust and scalable web applications. It was initially developed by Lawrence Journal-World in 2003 and released to the public under a BS
12 min read