|
| 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 | + class DecadeBornListFilter(admin.SimpleListFilter): |
| 58 | + # Human-readable title which will be displayed in the |
| 59 | + # right admin sidebar just above the filter options. |
| 60 | + title = _('decade born') |
| 61 | + |
| 62 | + # Parameter for the filter that will be used in the URL query. |
| 63 | + parameter_name = 'decade' |
| 64 | + |
| 65 | + def lookups(self, request, model_admin): |
| 66 | + """ |
| 67 | + Returns a list of tuples. The first element in each |
| 68 | + tuple is the coded value for the option that will |
| 69 | + appear in the URL query. The second element is the |
| 70 | + human-readable name for the option that will appear |
| 71 | + in the right sidebar. |
| 72 | + """ |
| 73 | + return ( |
| 74 | + ('80s', _('in the eighties')), |
| 75 | + ('90s', _('in the nineties')), |
| 76 | + ) |
| 77 | + |
| 78 | + def queryset(self, request, queryset): |
| 79 | + """ |
| 80 | + Returns the filtered queryset based on the value |
| 81 | + provided in the query string and retrievable via |
| 82 | + `self.value()`. |
| 83 | + """ |
| 84 | + # Compare the requested value (either '80s' or '90s') |
| 85 | + # to decide how to filter the queryset. |
| 86 | + if self.value() == '80s': |
| 87 | + return queryset.filter( |
| 88 | + birthday__gte=date(1980, 1, 1), |
| 89 | + birthday__lte=date(1989, 12, 31), |
| 90 | + ) |
| 91 | + if self.value() == '90s': |
| 92 | + return queryset.filter( |
| 93 | + birthday__gte=date(1990, 1, 1), |
| 94 | + birthday__lte=date(1999, 12, 31), |
| 95 | + ) |
| 96 | + |
| 97 | + class PersonAdmin(admin.ModelAdmin): |
| 98 | + list_filter = (DecadeBornListFilter,) |
| 99 | + |
| 100 | +.. note:: |
| 101 | + |
| 102 | + As a convenience, the ``HttpRequest`` object is passed to the ``lookups`` |
| 103 | + and ``queryset`` methods, for example:: |
| 104 | + |
| 105 | + class AuthDecadeBornListFilter(DecadeBornListFilter): |
| 106 | + |
| 107 | + def lookups(self, request, model_admin): |
| 108 | + if request.user.is_superuser: |
| 109 | + return super().lookups(request, model_admin) |
| 110 | + |
| 111 | + def queryset(self, request, queryset): |
| 112 | + if request.user.is_superuser: |
| 113 | + return super().queryset(request, queryset) |
| 114 | + |
| 115 | + Also as a convenience, the ``ModelAdmin`` object is passed to the |
| 116 | + ``lookups`` method, for example if you want to base the lookups on the |
| 117 | + available data:: |
| 118 | + |
| 119 | + class AdvancedDecadeBornListFilter(DecadeBornListFilter): |
| 120 | + |
| 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 | +.. note:: |
| 180 | + |
| 181 | + The :class:`~django.contrib.contenttypes.fields.GenericForeignKey` field is |
| 182 | + not supported. |
| 183 | + |
| 184 | +List filters typically appear only if the filter has more than one choice. A |
| 185 | +filter's ``has_output()`` method controls whether or not it appears. |
| 186 | + |
| 187 | +It is possible to specify a custom template for rendering a list filter:: |
| 188 | + |
| 189 | + class FilterWithCustomTemplate(admin.SimpleListFilter): |
| 190 | + template = "custom_template.html" |
| 191 | + |
| 192 | +See the default template provided by Django (``admin/filter.html``) for a |
| 193 | +concrete example. |
0 commit comments