Skip to content

django filter

Django-filter is a reusable Django application for allowing users to filter querysets dynamically.

Installation

pip install django-filter

Then add django_filters to your INSTALLED_APPS.

INSTALLED_APPS = [
    ...
    'django_filters',
]
Example

Define a Model

Let's say you have a simple model called Book:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publication_date = models.DateField()
    isbn = models.CharField(max_length=13)

    def __str__(self):
        return self.title

Create a FilterSet:

Next, you create a filter set for the Book model. A filter set defines which fields you want to filter and how:

import django_filters
from .models import Book

class BookFilter(django_filters.FilterSet):
    class Meta:
        model = Book
        fields = ['title', 'author', 'publication_date']

Create a View:

Then, you create a view that uses the filter set to filter the books. You can use Django's class-based views for this. Here, we'll use the generic ListView and integrate the filter:

from django.shortcuts import render
from django.views.generic import ListView
from django_filters.views import FilterView
from .models import Book
from .filters import BookFilter

class BookListView(FilterView, ListView):
    model = Book
    context_object_name = 'books'
    template_name = 'books/book_list.html'
    filterset_class = BookFilter

Create a Template:

Finally, create a template book_list.html to display the filtered list of books:

<!-- books/templates/books/book_list.html -->

<form method="get">
    {{ filter.form.as_p }}
    <button type="submit">Search</button>
</form>

<ul>
{% for book in books %}
    <li>{{ book.title }} by {{ book.author }} ({{ book.publication_date }})</li>
{% endfor %}
</ul>

Add URL Configuration:

Add a URL pattern to map to the BookListView:

from django.urls import path
from .views import BookListView

urlpatterns = [
    path('books/', BookListView.as_view(), name='book_list'),
]

How It Works

  • When you navigate to /books/, the BookListView will be rendered.
  • The BookFilter form will be displayed, allowing you to filter books by title, author, and publication_date.
  • Once you submit the form, the view will filter the Book objects based on the criteria you specified and display the filtered list.

This setup leverages django-filter to simplify the filtering of querysets, providing a clean and intuitive user interface for filtering data.


Reference