Создайте Admin SimpleListFilter
и примените приведенный ниже миксин
from django.utils.translation import gettext_lazy as _
class FilterMixin:
def choices(self, changelist):
yield {
'selected': self.value() is None,
'query_string': changelist.get_query_string(remove=[self.parameter_name, <b>'q'</b>]),
'display': _('All'),
}
for lookup, title in self.lookup_choices:
yield {
'selected': self.value() == str(lookup),
'query_string': changelist.get_query_string({self.parameter_name: lookup}, <b>remove=['q']</b>),
'display': title,
}
Полная база кода
#models.py
class Person(models.Model):
class GenderChoice(models.IntegerChoices):
MALE = 1
FEMALE = 2
OTHER = 3
name = models.CharField(max_length=20)
gender = models.IntegerField(choices=GenderChoice.choices)
def __str__(self):
return self.name
# admin.py
class GenderFilter(<b>FilterMixin, admin.SimpleListFilter</b>):
title = 'Gender'
parameter_name = 'gender'
def lookups(self, request, model_admin):
return Person.GenderChoice.choices
def queryset(self, request, queryset):
if self.value():
return queryset.filter(**{'gender': int(self.value())})
else:
return queryset
class PersonAdmin(admin.ModelAdmin):
search_fields = ('name',)
<b>list_filter = (GenderFilter,)</b>
admin.site.register(Person, PersonAdmin)