django-filter

25.2 · active · verified Sun Apr 05

Django-filter is a reusable Django application for allowing users to filter querysets dynamically. It uses a CalVer versioning scheme (Year.ReleaseNumber) and aims to support all current Django versions, matching Python versions, and the latest Django REST Framework.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a `FilterSet` for a Django model and integrating it with a standard Django class-based view (`ListView`) and a Django REST Framework `generics.ListAPIView`. For DRF, `DjangoFilterBackend` is added to `filter_backends` and the `filterset_class` or `filterset_fields` is specified on the view. Remember to add `django_filters` and `rest_framework` to `INSTALLED_APPS` in your Django `settings.py`.

import django_filters
from django.db import models
from django.views.generic import ListView
from rest_framework import generics
from rest_framework import serializers
from django_filters.rest_framework import DjangoFilterBackend

# 1. Define a Django Model
class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    release_date = models.DateField(null=True, blank=True)
    in_stock = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    class Meta:
        app_label = 'myapp' # Required for models in standalone snippets

# 2. Define a FilterSet for the Model
class ProductFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')
    price_gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt')
    price_lt = django_filters.NumberFilter(field_name='price', lookup_expr='lt')

    class Meta:
        model = Product
        fields = ['name', 'price', 'release_date', 'in_stock']

# 3. Use with a Django Class-Based View
# (Requires Django URL configuration and template setup)
class ProductListView(ListView):
    model = Product
    template_name = 'product_list.html' # Dummy template for example
    context_object_name = 'products'

    def get_queryset(self):
        queryset = super().get_queryset()
        filter = ProductFilter(self.request.GET, queryset=queryset)
        return filter.qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = ProductFilter(self.request.GET, queryset=self.get_queryset())
        return context

# 4. Use with Django REST Framework
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class ProductAPIView(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = ProductFilter # Or filterset_fields = ['name', 'price'] for simpler cases

# To run this code, you would need:
# - A Django project and app ('myapp').
# - Add 'django_filters' and 'rest_framework' to INSTALLED_APPS in settings.py.
# - Define URL patterns for ProductListView and ProductAPIView.
# - Run migrations to create the Product model.
# - Optionally, create 'product_list.html' template for the ListView.

view raw JSON →