Debian Codegraph @

docs/ref/filterset.txt

raw
1 =================
2 FilterSet Options
3 =================
4
5 This document provides a guide on using additional FilterSet features.
6
7 Meta options
8 ------------
9
10 - :ref:`model <model>`
11 - :ref:`fields <fields>`
12 - :ref:`exclude <exclude>`
13 - :ref:`form <form>`
14 - :ref:`filter_overrides <filter_overrides>`
15 - :ref:`unknown_field_behavior <unknown_field_behavior>`
16
17
18 .. _model:
19
20 Automatic filter generation with ``model``
21 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
22
23 The ``FilterSet`` is capable of automatically generating filters for a given
24 ``model``'s fields. Similar to Django's ``ModelForm``, filters are created
25 based on the underlying model field's type. This option must be combined with
26 either the ``fields`` or ``exclude`` option, which is the same requirement for
27 Django's ``ModelForm`` class, detailed `here`__.
28
29 __ https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#selecting-the-fields-to-use
30
31 .. code-block:: python
32
33 class UserFilter(django_filters.FilterSet):
34 class Meta:
35 model = User
36 fields = ['username', 'last_login']
37
38
39 .. _fields:
40
41 Declaring filterable ``fields``
42 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
43
44 The ``fields`` option is combined with ``model`` to automatically generate
45 filters. Note that generated filters will not overwrite filters declared on
46 the ``FilterSet``. The ``fields`` option accepts two syntaxes:
47
48 * a list of field names
49 * a dictionary of field names mapped to a list of lookups
50
51 .. code-block:: python
52
53 class UserFilter(django_filters.FilterSet):
54 class Meta:
55 model = User
56 fields = ['username', 'last_login']
57
58 # or
59
60 class UserFilter(django_filters.FilterSet):
61 class Meta:
62 model = User
63 fields = {
64 'username': ['exact', 'contains'],
65 'last_login': ['exact', 'year__gt'],
66 }
67
68 The list syntax will create an ``exact`` lookup filter for each field included
69 in ``fields``. The dictionary syntax will create a filter for each lookup
70 expression declared for its corresponding model field. These expressions may
71 include both transforms and lookups, as detailed in the `lookup reference`__.
72
73 __ https://docs.djangoproject.com/en/stable/ref/models/lookups/#module-django.db.models.lookups
74
75 Note that it is **not** necessary to include declared filters in a ``fields``
76 list - doing so will only affect the order in which fields appear on a FilterSet's form. Including declarative aliases in a
77 ``fields`` dict will raise an error.
78
79 .. code-block:: python
80
81 class UserFilter(django_filters.FilterSet):
82 username = filters.CharFilter()
83 login_timestamp = filters.IsoDateTimeFilter(field_name='last_login')
84
85 class Meta:
86 model = User
87 fields = {
88 'username': ['exact', 'contains'],
89 'login_timestamp': ['exact'],
90 }
91
92 TypeError("'Meta.fields' contains fields that are not defined on this FilterSet: login_timestamp")
93
94
95 .. _exclude:
96
97 Disable filter fields with ``exclude``
98 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
99
100 The ``exclude`` option accepts a blacklist of field names to exclude from
101 automatic filter generation. Note that this option will not disable filters
102 declared directly on the ``FilterSet``.
103
104 .. code-block:: python
105
106 class UserFilter(django_filters.FilterSet):
107 class Meta:
108 model = User
109 exclude = ['password']
110
111
112 .. _form:
113
114 Custom Forms using ``form``
115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
116
117 The inner ``Meta`` class also takes an optional ``form`` argument. This is a
118 form class from which ``FilterSet.form`` will subclass. This works similar to
119 the ``form`` option on a ``ModelAdmin.``
120
121
122 .. _filter_overrides:
123
124 Customise filter generation with ``filter_overrides``
125 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
126
127 The inner ``Meta`` class also takes an optional ``filter_overrides`` argument.
128 This is a map of model fields to filter classes with options::
129
130 class ProductFilter(django_filters.FilterSet):
131
132 class Meta:
133 model = Product
134 fields = ['name', 'release_date']
135 filter_overrides = {
136 models.CharField: {
137 'filter_class': django_filters.CharFilter,
138 'extra': lambda f: {
139 'lookup_expr': 'icontains',
140 },
141 },
142 models.BooleanField: {
143 'filter_class': django_filters.BooleanFilter,
144 'extra': lambda f: {
145 'widget': forms.CheckboxInput,
146 },
147 },
148 }
149
150
151
152 A possible usecase would be creating a custom filter to be able to filter on ``FileFields``
153 (``FileField`` filtering is hard to define in a generalised way, which is why there is no ``FileFilter``).
154
155 This example shows an override used to filter on a ``FileField``::
156
157 class Questionnaire(models.Model):
158 file = models.FileField(upload_to=questionnaire_path)
159
160 class QuestionnaireFilter(FilterSet):
161 class Meta:
162 model = Questionnaire
163 fields = ['file']
164 filter_overrides = {
165 models.FileField: {
166 'filter_class': CharFilter,
167 'extra': lambda f: {'lookup_expr': 'exact'},
168 },
169 }
170
171
172 .. _unknown_field_behavior:
173
174 Handling unknown fields with ``unknown_field_behavior``
175 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176
177 The ``unknown_field_behavior`` option specifies how unknown fields are handled
178 in a ``FilterSet``. You can set this option using the values of the
179 ``UnknownFieldBehavior`` enum:
180
181 - ``UnknownFieldBehavior.RAISE``: Raise an assertion error (default)
182 - ``UnknownFieldBehavior.WARN``: Issue a warning and ignore the field
183 - ``UnknownFieldBehavior.IGNORE``: Silently ignore the field
184
185 Note that both the ``WARN`` and ``IGNORE`` options do not include the unknown
186 field(s) in the list of filters.
187
188 .. code-block:: python
189
190 from django_filters import UnknownFieldBehavior
191
192 class UserFilter(django_filters.FilterSet):
193 class Meta:
194 model = User
195 fields = ['username', 'last_login']
196 unknown_field_behavior = UnknownFieldBehavior.WARN
197
198
199 Overriding ``FilterSet`` methods
200 --------------------------------
201
202 When overriding classmethods, calling ``super(MyFilterSet, cls)`` may result
203 in a ``NameError`` exception. This is due to the ``FilterSetMetaclass`` calling
204 these classmethods before the ``FilterSet`` class has been fully created.
205 There are two recommmended workarounds:
206
207 1. If using python 3.6 or newer, use the argumentless ``super()`` syntax.
208 2. For older versions of python, use an intermediate class. Ex::
209
210 class Intermediate(django_filters.FilterSet):
211
212 @classmethod
213 def method(cls, arg):
214 super(Intermediate, cls).method(arg)
215 ...
216
217 class ProductFilter(Intermediate):
218 class Meta:
219 model = Product
220 fields = ['...']
221
222 ``filter_for_lookup()``
223 ~~~~~~~~~~~~~~~~~~~~~~~
224
225 Prior to version 0.13.0, filter generation did not take into account the
226 ``lookup_expr`` used. This commonly caused malformed filters to be generated
227 for 'isnull', 'in', and 'range' lookups (as well as transformed lookups). The
228 current implementation provides the following behavior:
229
230 - 'isnull' lookups return a ``BooleanFilter``
231 - 'in' lookups return a filter derived from the CSV-based ``BaseInFilter``.
232 - 'range' lookups return a filter derived from the CSV-based ``BaseRangeFilter``.
233
234 If you want to override the ``filter_class`` and ``params`` used to instantiate
235 filters for a model field, you can override ``filter_for_lookup()``. Ex::
236
237 class ProductFilter(django_filters.FilterSet):
238 class Meta:
239 model = Product
240 fields = {
241 'release_date': ['exact', 'range'],
242 }
243
244 @classmethod
245 def filter_for_lookup(cls, f, lookup_type):
246 # override date range lookups
247 if isinstance(f, models.DateField) and lookup_type == 'range':
248 return django_filters.DateRangeFilter, {}
249
250 # use default behavior otherwise
251 return super().filter_for_lookup(f, lookup_type)
252
253
254 .. _filterset_factory:
255
256 Using ``filterset_factory``
257 ---------------------------
258
259 A ``FilterSet`` for a ``model`` can also be created by the
260 ``filterset_factory``, which creates a ``FilterSet`` with the ``model`` set in
261 the FilterSets Meta. You can pass a customized ``FilterSet`` class to the
262 ``filterset_factory``, which then uses this class a a base for the created
263 ``FilterSet``. Ex::
264
265 class CustomFilterSet(django_filters.FilterSet):
266 class Meta:
267 form = CustomFilterSetForm
268
269
270 filterset = filterset_factory(Product, filterset=CustomFilterSet)