| 1 |
.. _modeladmin-list-filters: |
| 2 |
|
| 3 |
=========================== |
| 4 |
``ModelAdmin`` List Filters |
| 5 |
=========================== |
| 6 |
|
| 7 |
.. currentmodule:: django.contrib.admin |
| 8 |
|
| 9 |
``ModelAdmin`` classes can define list filters that appear in the right sidebar |
| 10 |
of the change list page of the admin, as illustrated in the following |
| 11 |
screenshot: |
| 12 |
|
| 13 |
.. image:: _images/list_filter.png |
| 14 |
|
| 15 |
To activate per-field filtering, set :attr:`ModelAdmin.list_filter` to a list |
| 16 |
or tuple of elements, where each element is one of the following types: |
| 17 |
|
| 18 |
- A field name. |
| 19 |
- A subclass of ``django.contrib.admin.SimpleListFilter``. |
| 20 |
- A 2-tuple containing a field name and a subclass of |
| 21 |
``django.contrib.admin.FieldListFilter``. |
| 22 |
|
| 23 |
See the examples below for discussion of each of these options for defining |
| 24 |
``list_filter``. |
| 25 |
|
| 26 |
Using a field name |
| 27 |
================== |
| 28 |
|
| 29 |
The simplest option is to specify the required field names from your model. |
| 30 |
|
| 31 |
Each specified field should be either a ``BooleanField``, ``CharField``, |
| 32 |
``DateField``, ``DateTimeField``, ``IntegerField``, ``ForeignKey`` or |
| 33 |
``ManyToManyField``, for example:: |
| 34 |
|
| 35 |
class PersonAdmin(admin.ModelAdmin): |
| 36 |
list_filter = ["is_staff", "company"] |
| 37 |
|
| 38 |
Field names in ``list_filter`` can also span relations |
| 39 |
using the ``__`` lookup, for example:: |
| 40 |
|
| 41 |
class PersonAdmin(admin.UserAdmin): |
| 42 |
list_filter = ["company__name"] |
| 43 |
|
| 44 |
Using a ``SimpleListFilter`` |
| 45 |
============================ |
| 46 |
|
| 47 |
For custom filtering, you can define your own list filter by subclassing |
| 48 |
``django.contrib.admin.SimpleListFilter``. You need to provide the ``title`` |
| 49 |
and ``parameter_name`` attributes, and override the ``lookups`` and |
| 50 |
``queryset`` methods, e.g.:: |
| 51 |
|
| 52 |
from datetime import date |
| 53 |
|
| 54 |
from django.contrib import admin |
| 55 |
from django.utils.translation import gettext_lazy as _ |
| 56 |
|
| 57 |
|
| 58 |
class DecadeBornListFilter(admin.SimpleListFilter): |
| 59 |
# Human-readable title which will be displayed in the |
| 60 |
# right admin sidebar just above the filter options. |
| 61 |
title = _("decade born") |
| 62 |
|
| 63 |
# Parameter for the filter that will be used in the URL query. |
| 64 |
parameter_name = "decade" |
| 65 |
|
| 66 |
def lookups(self, request, model_admin): |
| 67 |
""" |
| 68 |
Returns a list of tuples. The first element in each |
| 69 |
tuple is the coded value for the option that will |
| 70 |
appear in the URL query. The second element is the |
| 71 |
human-readable name for the option that will appear |
| 72 |
in the right sidebar. |
| 73 |
""" |
| 74 |
return [ |
| 75 |
("80s", _("in the eighties")), |
| 76 |
("90s", _("in the nineties")), |
| 77 |
] |
| 78 |
|
| 79 |
def queryset(self, request, queryset): |
| 80 |
""" |
| 81 |
Returns the filtered queryset based on the value |
| 82 |
provided in the query string and retrievable via |
| 83 |
`self.value()`. |
| 84 |
""" |
| 85 |
# Compare the requested value (either '80s' or '90s') |
| 86 |
# to decide how to filter the queryset. |
| 87 |
if self.value() == "80s": |
| 88 |
return queryset.filter( |
| 89 |
birthday__gte=date(1980, 1, 1), |
| 90 |
birthday__lte=date(1989, 12, 31), |
| 91 |
) |
| 92 |
if self.value() == "90s": |
| 93 |
return queryset.filter( |
| 94 |
birthday__gte=date(1990, 1, 1), |
| 95 |
birthday__lte=date(1999, 12, 31), |
| 96 |
) |
| 97 |
|
| 98 |
|
| 99 |
class PersonAdmin(admin.ModelAdmin): |
| 100 |
list_filter = [DecadeBornListFilter] |
| 101 |
|
| 102 |
.. note:: |
| 103 |
|
| 104 |
As a convenience, the ``HttpRequest`` object is passed to the ``lookups`` |
| 105 |
and ``queryset`` methods, for example:: |
| 106 |
|
| 107 |
class AuthDecadeBornListFilter(DecadeBornListFilter): |
| 108 |
def lookups(self, request, model_admin): |
| 109 |
if request.user.is_superuser: |
| 110 |
return super().lookups(request, model_admin) |
| 111 |
|
| 112 |
def queryset(self, request, queryset): |
| 113 |
if request.user.is_superuser: |
| 114 |
return super().queryset(request, queryset) |
| 115 |
|
| 116 |
Also as a convenience, the ``ModelAdmin`` object is passed to the |
| 117 |
``lookups`` method, for example if you want to base the lookups on the |
| 118 |
available data:: |
| 119 |
|
| 120 |
class AdvancedDecadeBornListFilter(DecadeBornListFilter): |
| 121 |
def lookups(self, request, model_admin): |
| 122 |
""" |
| 123 |
Only show the lookups if there actually is |
| 124 |
anyone born in the corresponding decades. |
| 125 |
""" |
| 126 |
qs = model_admin.get_queryset(request) |
| 127 |
if qs.filter( |
| 128 |
birthday__gte=date(1980, 1, 1), |
| 129 |
birthday__lte=date(1989, 12, 31), |
| 130 |
).exists(): |
| 131 |
yield ("80s", _("in the eighties")) |
| 132 |
if qs.filter( |
| 133 |
birthday__gte=date(1990, 1, 1), |
| 134 |
birthday__lte=date(1999, 12, 31), |
| 135 |
).exists(): |
| 136 |
yield ("90s", _("in the nineties")) |
| 137 |
|
| 138 |
Using a field name and an explicit ``FieldListFilter`` |
| 139 |
====================================================== |
| 140 |
|
| 141 |
Finally, if you wish to specify an explicit filter type to use with a field you |
| 142 |
may provide a ``list_filter`` item as a 2-tuple, where the first element is a |
| 143 |
field name and the second element is a class inheriting from |
| 144 |
``django.contrib.admin.FieldListFilter``, for example:: |
| 145 |
|
| 146 |
class PersonAdmin(admin.ModelAdmin): |
| 147 |
list_filter = [ |
| 148 |
("is_staff", admin.BooleanFieldListFilter), |
| 149 |
] |
| 150 |
|
| 151 |
Here the ``is_staff`` field will use the ``BooleanFieldListFilter``. Specifying |
| 152 |
only the field name, fields will automatically use the appropriate filter for |
| 153 |
most cases, but this format allows you to control the filter used. |
| 154 |
|
| 155 |
The following examples show available filter classes that you need to opt-in |
| 156 |
to use. |
| 157 |
|
| 158 |
You can limit the choices of a related model to the objects involved in |
| 159 |
that relation using ``RelatedOnlyFieldListFilter``:: |
| 160 |
|
| 161 |
class BookAdmin(admin.ModelAdmin): |
| 162 |
list_filter = [ |
| 163 |
("author", admin.RelatedOnlyFieldListFilter), |
| 164 |
] |
| 165 |
|
| 166 |
Assuming ``author`` is a ``ForeignKey`` to a ``User`` model, this will |
| 167 |
limit the ``list_filter`` choices to the users who have written a book, |
| 168 |
instead of listing all users. |
| 169 |
|
| 170 |
You can filter empty values using ``EmptyFieldListFilter``, which can |
| 171 |
filter on both empty strings and nulls, depending on what the field |
| 172 |
allows to store:: |
| 173 |
|
| 174 |
class BookAdmin(admin.ModelAdmin): |
| 175 |
list_filter = [ |
| 176 |
("title", admin.EmptyFieldListFilter), |
| 177 |
] |
| 178 |
|
| 179 |
By defining a filter using the ``__in`` lookup, it is possible to filter for |
| 180 |
any of a group of values. You need to override the ``expected_parameters`` |
| 181 |
method, and the specify the ``lookup_kwargs`` attribute with the appropriate |
| 182 |
field name. By default, multiple values in the query string will be separated |
| 183 |
with commas, but this can be customized via the ``list_separator`` attribute. |
| 184 |
The following example shows such a filter using the vertical-pipe character as |
| 185 |
the separator:: |
| 186 |
|
| 187 |
class FilterWithCustomSeparator(admin.FieldListFilter): |
| 188 |
# custom list separator that should be used to separate values. |
| 189 |
list_separator = "|" |
| 190 |
|
| 191 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 192 |
self.lookup_kwarg = "%s__in" % field_path |
| 193 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 194 |
|
| 195 |
def expected_parameters(self): |
| 196 |
return [self.lookup_kwarg] |
| 197 |
|
| 198 |
.. note:: |
| 199 |
|
| 200 |
The :class:`~django.contrib.contenttypes.fields.GenericForeignKey` field is |
| 201 |
not supported. |
| 202 |
|
| 203 |
List filters typically appear only if the filter has more than one choice. A |
| 204 |
filter's ``has_output()`` method controls whether or not it appears. |
| 205 |
|
| 206 |
It is possible to specify a custom template for rendering a list filter:: |
| 207 |
|
| 208 |
class FilterWithCustomTemplate(admin.SimpleListFilter): |
| 209 |
template = "custom_template.html" |
| 210 |
|
| 211 |
See the default template provided by Django (``admin/filter.html``) for a |
| 212 |
concrete example. |
| 213 |
|
| 214 |
.. _facet-filters: |
| 215 |
|
| 216 |
Facets |
| 217 |
====== |
| 218 |
|
| 219 |
By default, counts for each filter, known as facets, can be shown by toggling |
| 220 |
on via the admin UI. These counts will update according to the currently |
| 221 |
applied filters. See :attr:`ModelAdmin.show_facets` for more details. |