Creating Custom Semantic Filters
Explore how to create custom semantic filters in Django admin by subclassing SimpleListFilter. Learn to integrate complex business logic, timezone-aware queryset filtering, and combine these with standard filters to enhance data discovery and admin user experience.
The standard list_filter array handles direct database columns perfectly. If you want to filter by an exact date or a specific author, you pass the field name, and Django builds the sidebar. However, standard field filters cannot handle complex business logic. If administrators need to filter questions based on computed states, like whether a question is actively published relative to the current time, we must build a custom filter.
The mechanics of custom filters
To create a business-logic-driven filter, we write a custom class that inherits from django.contrib.admin.SimpleListFilter. Before writing the code, we must understand the underlying request flow that powers this class.
When an administrator interacts with a custom filter, the system executes a specific sequence of operations:
The user clicks a human-readable label in the right sidebar of the
changelist.Django intercepts this click and appends a query ...