ModelAdmin List Filters

ModelAdmin classes can define list filters that appear in the right sidebar of the change list page of the admin, as illustrated in the following screenshot:

../../../../_images/list_filter.png

To activate per-field filtering, set ModelAdmin.list_filter to a list or tuple of elements, where each element is one of the following types:

  • A field name.
  • A subclass of django.contrib.admin.SimpleListFilter.
  • A 2-tuple containing a field name and a subclass of django.contrib.admin.FieldListFilter.

See the examples below for discussion of each of these options for defining list_filter.

Using a field name

The simplest option is to specify the required field names from your model.

Each specified field should be either a BooleanField, CharField, DateField, DateTimeField, IntegerField, ForeignKey or ManyToManyField, for example:

  1. class PersonAdmin(admin.ModelAdmin):
  2. list_filter = ('is_staff', 'company')

list_filter 中的字段名也可以使用 __ 查找来跨越关系,例如:

  1. class PersonAdmin(admin.UserAdmin):
  2. list_filter = ('company__name',)

Using a SimpleListFilter

For custom filtering, you can define your own list filter by subclassing django.contrib.admin.SimpleListFilter. You need to provide the title and parameter_name attributes, and override the lookups and queryset methods, e.g.:

  1. from datetime import date
  2. from django.contrib import admin
  3. from django.utils.translation import gettext_lazy as _
  4. class DecadeBornListFilter(admin.SimpleListFilter):
  5. # Human-readable title which will be displayed in the
  6. # right admin sidebar just above the filter options.
  7. title = _('decade born')
  8. # Parameter for the filter that will be used in the URL query.
  9. parameter_name = 'decade'
  10. def lookups(self, request, model_admin):
  11. """
  12. Returns a list of tuples. The first element in each
  13. tuple is the coded value for the option that will
  14. appear in the URL query. The second element is the
  15. human-readable name for the option that will appear
  16. in the right sidebar.
  17. """
  18. return (
  19. ('80s', _('in the eighties')),
  20. ('90s', _('in the nineties')),
  21. )
  22. def queryset(self, request, queryset):
  23. """
  24. Returns the filtered queryset based on the value
  25. provided in the query string and retrievable via
  26. `self.value()`.
  27. """
  28. # Compare the requested value (either '80s' or '90s')
  29. # to decide how to filter the queryset.
  30. if self.value() == '80s':
  31. return queryset.filter(
  32. birthday__gte=date(1980, 1, 1),
  33. birthday__lte=date(1989, 12, 31),
  34. )
  35. if self.value() == '90s':
  36. return queryset.filter(
  37. birthday__gte=date(1990, 1, 1),
  38. birthday__lte=date(1999, 12, 31),
  39. )
  40. class PersonAdmin(admin.ModelAdmin):
  41. list_filter = (DecadeBornListFilter,)

备注

为方便起见,HttpRequest 对象被传递给 lookupsqueryset 方法,例如:

  1. class AuthDecadeBornListFilter(DecadeBornListFilter):
  2. def lookups(self, request, model_admin):
  3. if request.user.is_superuser:
  4. return super().lookups(request, model_admin)
  5. def queryset(self, request, queryset):
  6. if request.user.is_superuser:
  7. return super().queryset(request, queryset)

另外,为了方便起见,ModelAdmin 对象被传递给 lookups 方法,例如,如果你想根据现有数据进行查找:

  1. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
  2. def lookups(self, request, model_admin):
  3. """
  4. Only show the lookups if there actually is
  5. anyone born in the corresponding decades.
  6. """
  7. qs = model_admin.get_queryset(request)
  8. if qs.filter(
  9. birthday__gte=date(1980, 1, 1),
  10. birthday__lte=date(1989, 12, 31),
  11. ).exists():
  12. yield ('80s', _('in the eighties'))
  13. if qs.filter(
  14. birthday__gte=date(1990, 1, 1),
  15. birthday__lte=date(1999, 12, 31),
  16. ).exists():
  17. yield ('90s', _('in the nineties'))

Using a field name and an explicit FieldListFilter

Finally, if you wish to specify an explicit filter type to use with a field you may provide a list_filter item as a 2-tuple, where the first element is a field name and the second element is a class inheriting from django.contrib.admin.FieldListFilter, for example:

  1. class PersonAdmin(admin.ModelAdmin):
  2. list_filter = (
  3. ('is_staff', admin.BooleanFieldListFilter),
  4. )

Here the is_staff field will use the BooleanFieldListFilter. Specifying only the field name, fields will automatically use the appropriate filter for most cases, but this format allows you to control the filter used.

The following examples show available filter classes that you need to opt-in to use.

你可以使用 RelatedOnlyFieldListFilter 将相关模型的选择限制在该关系所涉及的对象上:

  1. class BookAdmin(admin.ModelAdmin):
  2. list_filter = (
  3. ('author', admin.RelatedOnlyFieldListFilter),
  4. )

Assuming author is a ForeignKey to a User model, this will limit the list_filter choices to the users who have written a book, instead of listing all users.

你可以使用 EmptyFieldListFilter 来过滤空值,它既可以过滤空字符串也可以过滤空值,这取决于字段允许存储的内容:

  1. class BookAdmin(admin.ModelAdmin):
  2. list_filter = (
  3. ('title', admin.EmptyFieldListFilter),
  4. )

By defining a filter using the __in lookup, it is possible to filter for any of a group of values. You need to override the expected_parameters method, and the specify the lookup_kwargs attribute with the appropriate field name. By default, multiple values in the query string will be separated with commas, but this can be customized via the list_separator attribute. The following example shows such a filter using the vertical-pipe character as the separator:

  1. class FilterWithCustomSeparator(admin.FieldListFilter):
  2. # custom list separator that should be used to separate values.
  3. list_separator = '|'
  4. def __init__(self, field, request, params, model, model_admin, field_path):
  5. self.lookup_kwarg = '%s__in' % field_path
  6. super().__init__(field, request, params, model, model_admin, field_path)
  7. def expected_parameters(self):
  8. return [self.lookup_kwarg]

备注

不支持 GenericForeignKey 字段。

List filters typically appear only if the filter has more than one choice. A filter’s has_output() method controls whether or not it appears.

可以指定一个自定义模板来呈现列表过滤器:

  1. class FilterWithCustomTemplate(admin.SimpleListFilter):
  2. template = "custom_template.html"

具体的例子请看 Django 提供的默认模板(admin/filter.html)。