django filter
Django-filter is a reusable Django application for allowing users to filter querysets dynamically.
Installation
Then add django_filters
to your INSTALLED_APPS.
Example
Define a Model
Let's say you have a simple model called Book
:
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:
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:
How It Works
- When you navigate to
/books/
, theBookListView
will be rendered. - The BookFilter form will be displayed, allowing you to filter books by
title
,author
, andpublication_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.