how to use django-filters with viewset
Django filters provide a convenient way to filter querysets based on specific criteria. Here's how you can use django-filters with a viewset:
Step 1: Install django-filters Make sure django-filters is installed in your Django project. You can do this by running the following command:
pip install django-filters
Step 2: Import necessary modules In your viewset file, import the necessary modules:
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
Step 3: Define your filterset class
Create a filterset class that inherits from django_filters.FilterSet
. This class will define the filters you want to apply to your queryset. For example, let's say you have a model called Product
and you want to filter the queryset based on the name
field:
import django_filters
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Product
fields = ['name']
In the above example, we define a filter for the name
field using CharFilter
and set the lookup_expr
to 'icontains'
to perform a case-insensitive search.
Step 4: Configure the filter backend
In your viewset class, specify the filter backend to use. You can do this by adding the filter_backends
attribute and setting it to include DjangoFilterBackend
. For example:
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = ProductFilter
In the above example, we set the filter_backends
attribute to include DjangoFilterBackend
and the filterset_class
attribute to point to our ProductFilter
class.
Step 5: Test the filtering Now you can test the filtering by making a GET request to your viewset endpoint with the desired filter parameters. For example, to filter products by name, you can make a request like this:
GET /products/?name=apple
This will return all products that have the word "apple" in their name.
That's it! You have successfully integrated django-filters with your viewset. You can add more filters to your filterset class as needed, and django-filters will handle the filtering logic for you.