5.4. Admin Filters
list_filter
>>>
... class SalaryFilter(admin.SimpleListFilter):
... title = _('Salary')
... parameter_name = 'salary'
...
... def lookups(self, request, model_admin):
... return (
... ('low', _('Low')),
... ('medium', _('Medium')),
... ('high', _('High')),
... )
...
... def queryset(self, request, queryset):
... match self.value():
... case 'low': return queryset.filter(salary__lt=5_000)
... case 'medium': return queryset.filter(salary__gte=5_000, salary__lt=10_000)
... case 'high': return queryset.filter(salary__gte=10_000)
...
...
... @admin.register(Employee)
... class EmployeeAdmin(BaseAdmin):
... list_filter = [SalaryFilter]
5.4.1. Use Case - 1
>>>
... from django.contrib import admin
... from django.utils.translation import gettext_lazy as _
... from datetime import date
...
...
... class AgeFilter(admin.SimpleListFilter):
... # Human-readable title which will be displayed in the
... # right admin sidebar just above the filter options.
... title = _('Age')
...
... # Parameter for the filter that will be used in the URL query.
... parameter_name = 'age'
...
... def lookups(self, request, model_admin):
... return [
... ('unknown', _('Not Specified')),
... ('junior', _('0-18')),
... ('adult', _('18-65')),
... ('senior', _('65+')),
... ]
...
... def queryset(self, request, queryset):
... if self.value() == 'unknown':
... return queryset.filter(birthdate=None)
... if self.value() == 'junior':
... start = date.today() - datetime.timedelta(days=0*365)
... end = date.today() - datetime.timedelta(days=18*365)
... return queryset.filter(birthdate__gte=start, birthdate__lt=end)
... if self.value() == 'adult':
... start = date.today() - datetime.timedelta(days=18*365)
... end = date.today() - datetime.timedelta(days=65*365)
... return queryset.filter(birthdate__gte=start, birthdate__lt=end)
... if self.value() == 'senior':
... start = date.today() - datetime.timedelta(days=65*365)
... return queryset.filter(birthdate__gte=start)