Filtering Data in Django Rest Framework
In this tutorial, we will explore how to filter data using the Django Rest Framework (DRF). Filtering data allows us to retrieve specific subsets of data from our API endpoints based on certain conditions.
We'll use the 'students' model and serializer we created in our previous tutorials.
Filtering by a Single Field
Let's start by filtering students based on their city.
from rest_framework.generics import ListAPIView
from .models import Students
from .serializers import StudentsSerializer
class StudentsListCreateView(ListAPIView):
serializer_class = StudentsSerializer
def get_queryset(self):
city = self.kwargs['city']
queryset = Students.objects.filter(City=city)
return queryset
In this example, we're using a URL parameter city to filter students by the specified city.
Add the URL pattern
urlpatterns = [
path('students/city/<str:city>/', StudentsByCityView.as_view(), name='students-by-city'),
]
Now, let's check if the data in our API view is getting filtered or not when using the city parameter.
Output
Filtering with Multiple Parameters
We can filter data using multiple parameters. Let's filter students based on both their city and roll number.
from rest_framework import generics
from .models import Students
from .serializers import StudentsSerializer
class StudentsListCreateView(generics.ListAPIView):
serializer_class = StudentsSerializer
def get_queryset(self):
city = self.request.query_params.get('city')
roll = self.request.query_params.get('roll')
queryset = Students.objects.all()
if city:
queryset = queryset.filter(City=city)
if roll:
queryset = queryset.filter(Roll=roll)
return queryset
In this example, we're using query parameters (city and roll) to filter students.
Add the URL pattern
urlpatterns = [
path('students/filter/', StudentsFilterView.as_view(), name='students-filter'),
]
Now, let's check if the data in our API view is getting filtered or not.
Output