| 1 |
================ |
| 2 |
Filter Reference |
| 3 |
================ |
| 4 |
|
| 5 |
This is a reference document with a list of the filters and their arguments. |
| 6 |
|
| 7 |
.. _core-arguments: |
| 8 |
|
| 9 |
Core Arguments |
| 10 |
-------------- |
| 11 |
|
| 12 |
The following are the core arguments that apply to all filters. Note that they |
| 13 |
are joined to construct the complete `lookup expression`_ that is the left hand |
| 14 |
side of the ORM ``.filter()`` call. |
| 15 |
|
| 16 |
.. _`lookup expression`: https://docs.djangoproject.com/en/stable/ref/models/lookups/#module-django.db.models.lookups |
| 17 |
|
| 18 |
``field_name`` |
| 19 |
~~~~~~~~~~~~~~ |
| 20 |
|
| 21 |
The name of the model field that is filtered against. If this argument is not |
| 22 |
provided, it defaults the filter's attribute name on the ``FilterSet`` class. |
| 23 |
Field names can traverse relationships by joining the related parts with the ORM |
| 24 |
lookup separator (``__``). e.g., a product's ``manufacturer__name``. |
| 25 |
|
| 26 |
``lookup_expr`` |
| 27 |
~~~~~~~~~~~~~~~ |
| 28 |
|
| 29 |
The `field lookup`_ that should be performed in the filter call. Defaults to |
| 30 |
``exact``. The ``lookup_expr`` can contain transforms if the expression parts |
| 31 |
are joined by the ORM lookup separator (``__``). e.g., filter a datetime by its |
| 32 |
year part ``year__gt``. |
| 33 |
|
| 34 |
.. _`Field lookup`: https://docs.djangoproject.com/en/stable/ref/models/querysets/#field-lookups |
| 35 |
|
| 36 |
.. _keyword-only-arguments: |
| 37 |
|
| 38 |
Keyword-only Arguments |
| 39 |
---------------------- |
| 40 |
|
| 41 |
The following are optional arguments that can be used to modify the behavior of |
| 42 |
all filters. |
| 43 |
|
| 44 |
``label`` |
| 45 |
~~~~~~~~~ |
| 46 |
|
| 47 |
The label as it will appear in the HTML, analogous to a form field's label |
| 48 |
argument. If a label is not provided, a verbose label will be generated based |
| 49 |
on the field ``field_name`` and the parts of the ``lookup_expr`` |
| 50 |
(see: :ref:`verbose-lookups-setting`). |
| 51 |
|
| 52 |
.. _filter-method: |
| 53 |
|
| 54 |
``method`` |
| 55 |
~~~~~~~~~~ |
| 56 |
|
| 57 |
An optional argument that tells the filter how to handle the queryset. It can |
| 58 |
accept either a callable or the name of a method on the ``FilterSet``. The |
| 59 |
callable receives a ``QuerySet``, the name of the model field to filter on, and |
| 60 |
the value to filter with. It should return a filtered ``Queryset``. |
| 61 |
|
| 62 |
Note that the value is validated by the ``Filter.field``, so raw value |
| 63 |
transformation and empty value checking should be unnecessary. |
| 64 |
|
| 65 |
.. code-block:: python |
| 66 |
|
| 67 |
class F(FilterSet): |
| 68 |
"""Filter for Books by if books are published or not""" |
| 69 |
published = BooleanFilter(field_name='published_on', method='filter_published') |
| 70 |
|
| 71 |
def filter_published(self, queryset, name, value): |
| 72 |
# construct the full lookup expression. |
| 73 |
lookup = '__'.join([name, 'isnull']) |
| 74 |
return queryset.filter(**{lookup: False}) |
| 75 |
|
| 76 |
# alternatively, you could opt to hardcode the lookup. e.g., |
| 77 |
# return queryset.filter(published_on__isnull=False) |
| 78 |
|
| 79 |
class Meta: |
| 80 |
model = Book |
| 81 |
fields = ['published'] |
| 82 |
|
| 83 |
|
| 84 |
# Callables may also be defined out of the class scope. |
| 85 |
def filter_not_empty(queryset, name, value): |
| 86 |
lookup = '__'.join([name, 'isnull']) |
| 87 |
return queryset.filter(**{lookup: False}) |
| 88 |
|
| 89 |
class F(FilterSet): |
| 90 |
"""Filter for Books by if books are published or not""" |
| 91 |
published = BooleanFilter(field_name='published_on', method=filter_not_empty) |
| 92 |
|
| 93 |
class Meta: |
| 94 |
model = Book |
| 95 |
fields = ['published'] |
| 96 |
|
| 97 |
|
| 98 |
``distinct`` |
| 99 |
~~~~~~~~~~~~ |
| 100 |
|
| 101 |
A boolean that specifies whether the Filter will use distinct on the queryset. |
| 102 |
This option can be used to eliminate duplicate results when using filters that |
| 103 |
span relationships. Defaults to ``False``. |
| 104 |
|
| 105 |
``exclude`` |
| 106 |
~~~~~~~~~~~ |
| 107 |
|
| 108 |
A boolean that specifies whether the Filter should use ``filter`` or ``exclude`` |
| 109 |
on the queryset. Defaults to ``False``. |
| 110 |
|
| 111 |
``required`` |
| 112 |
~~~~~~~~~~~~ |
| 113 |
|
| 114 |
A boolean that specifies whether the Filter is required or not. Defaults to ``False``. |
| 115 |
|
| 116 |
|
| 117 |
``**kwargs`` |
| 118 |
~~~~~~~~~~~~ |
| 119 |
|
| 120 |
Any additional keyword arguments are stored as the ``extra`` parameter on the |
| 121 |
filter. They are provided to the accompanying form ``Field`` and can be used to |
| 122 |
provide arguments like ``choices``. Some field-related arguments: |
| 123 |
|
| 124 |
``widget`` |
| 125 |
"""""""""" |
| 126 |
|
| 127 |
The django.form Widget class which will represent the ``Filter``. In addition |
| 128 |
to the widgets that are included with Django that you can use there are |
| 129 |
additional ones that django-filter provides which may be useful: |
| 130 |
|
| 131 |
* :ref:`LinkWidget <link-widget>` -- this displays the options in a manner |
| 132 |
similar to the way the Django Admin does, as a series of links. The link |
| 133 |
for the selected option will have ``class="selected"``. |
| 134 |
* :ref:`BooleanWidget <boolean-widget>` -- this widget converts its input |
| 135 |
into Python's True/False values. It will convert all case variations of |
| 136 |
``True`` and ``False`` into the internal Python values. |
| 137 |
* :ref:`CSVWidget <csv-widget>` -- this widget expects a comma separated |
| 138 |
value and converts it into a list of string values. It is expected that |
| 139 |
the field class handle a list of values as well as type conversion. |
| 140 |
* :ref:`RangeWidget <range-widget>` -- this widget is used with ``RangeFilter`` |
| 141 |
to generate two form input elements using a single field. |
| 142 |
|
| 143 |
|
| 144 |
ModelChoiceFilter and ModelMultipleChoiceFilter arguments |
| 145 |
--------------------------------------------------------- |
| 146 |
|
| 147 |
These arguments apply specifically to ModelChoiceFilter and |
| 148 |
ModelMultipleChoiceFilter only. |
| 149 |
|
| 150 |
``queryset`` |
| 151 |
~~~~~~~~~~~~ |
| 152 |
|
| 153 |
``ModelChoiceFilter`` and ``ModelMultipleChoiceFilter`` require a queryset to |
| 154 |
operate on which must be passed as a kwarg. |
| 155 |
|
| 156 |
``to_field_name`` |
| 157 |
~~~~~~~~~~~~~~~~~ |
| 158 |
|
| 159 |
If you pass in ``to_field_name`` (which gets forwarded to the Django field), |
| 160 |
it will be used also in the default ``get_filter_predicate`` implementation |
| 161 |
as the model's attribute. |
| 162 |
|
| 163 |
|
| 164 |
Filters |
| 165 |
------- |
| 166 |
|
| 167 |
``CharFilter`` |
| 168 |
~~~~~~~~~~~~~~ |
| 169 |
|
| 170 |
This filter does simple character matches, used with ``CharField`` and |
| 171 |
``TextField`` by default. |
| 172 |
|
| 173 |
``UUIDFilter`` |
| 174 |
~~~~~~~~~~~~~~ |
| 175 |
|
| 176 |
This filter matches UUID values, used with ``models.UUIDField`` by default. |
| 177 |
|
| 178 |
``BooleanFilter`` |
| 179 |
~~~~~~~~~~~~~~~~~ |
| 180 |
|
| 181 |
This filter matches a boolean, either ``True`` or ``False``, used with |
| 182 |
``BooleanField`` and ``NullBooleanField`` by default. |
| 183 |
|
| 184 |
.. _choice-filter: |
| 185 |
|
| 186 |
``ChoiceFilter`` |
| 187 |
~~~~~~~~~~~~~~~~ |
| 188 |
|
| 189 |
This filter matches values in its ``choices`` argument. The ``choices`` must be |
| 190 |
explicitly passed when the filter is declared on the ``FilterSet``. For example, |
| 191 |
|
| 192 |
.. code-block:: python |
| 193 |
|
| 194 |
class User(models.Model): |
| 195 |
username = models.CharField(max_length=255) |
| 196 |
first_name = SubCharField(max_length=100) |
| 197 |
last_name = SubSubCharField(max_length=100) |
| 198 |
|
| 199 |
status = models.IntegerField(choices=STATUS_CHOICES, default=0) |
| 200 |
|
| 201 |
STATUS_CHOICES = ( |
| 202 |
(0, 'Regular'), |
| 203 |
(1, 'Manager'), |
| 204 |
(2, 'Admin'), |
| 205 |
) |
| 206 |
|
| 207 |
class F(FilterSet): |
| 208 |
status = ChoiceFilter(choices=STATUS_CHOICES) |
| 209 |
class Meta: |
| 210 |
model = User |
| 211 |
fields = ['status'] |
| 212 |
|
| 213 |
|
| 214 |
``ChoiceFilter`` also has arguments that enable a choice for not filtering, as |
| 215 |
well as a choice for filtering by ``None`` values. Each of the arguments have a |
| 216 |
corresponding global setting (:doc:`/ref/settings`). |
| 217 |
|
| 218 |
* ``empty_label``: The display label to use for the select choice to not filter. |
| 219 |
The choice may be disabled by setting this argument to ``None``. Defaults to |
| 220 |
``FILTERS_EMPTY_CHOICE_LABEL``. |
| 221 |
* ``null_label``: The display label to use for the choice to filter by ``None`` |
| 222 |
values. The choice may be disabled by setting this argument to ``None``. |
| 223 |
Defaults to ``FILTERS_NULL_CHOICE_LABEL``. |
| 224 |
* ``null_value``: The special value to match to enable filtering by ``None`` |
| 225 |
values. This value defaults ``FILTERS_NULL_CHOICE_VALUE`` and needs to be |
| 226 |
a non-empty value (``''``, ``None``, ``[]``, ``()``, ``{}``). |
| 227 |
|
| 228 |
|
| 229 |
``TypedChoiceFilter`` |
| 230 |
~~~~~~~~~~~~~~~~~~~~~ |
| 231 |
|
| 232 |
The same as ``ChoiceFilter`` with the added possibility to convert value to |
| 233 |
match against. This could be done by using `coerce` parameter. |
| 234 |
An example use-case is limiting boolean choices to match against so only |
| 235 |
some predefined strings could be used as input of a boolean filter:: |
| 236 |
|
| 237 |
import django_filters |
| 238 |
from distutils.util import strtobool |
| 239 |
|
| 240 |
BOOLEAN_CHOICES = (('false', 'False'), ('true', 'True'),) |
| 241 |
|
| 242 |
class YourFilterSet(django_filters.FilterSet): |
| 243 |
... |
| 244 |
flag = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, |
| 245 |
coerce=strtobool) |
| 246 |
|
| 247 |
|
| 248 |
``MultipleChoiceFilter`` |
| 249 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 250 |
|
| 251 |
The same as ``ChoiceFilter`` except the user can select multiple choices |
| 252 |
and the filter will form the OR of these choices by default to match items. |
| 253 |
The filter will form the AND of the selected choices when the ``conjoined=True`` |
| 254 |
argument is passed to this class. |
| 255 |
|
| 256 |
Multiple choices are represented in the query string by reusing the same key with |
| 257 |
different values (e.g. ''?status=Regular&status=Admin''). |
| 258 |
|
| 259 |
``distinct`` defaults to ``True`` as to-many relationships will generally require this. |
| 260 |
|
| 261 |
Advanced Use: Depending on your application logic, when all or no choices are |
| 262 |
selected, filtering may be a noop. In this case you may wish to avoid the |
| 263 |
filtering overhead, particularly of the `distinct` call. |
| 264 |
|
| 265 |
Set `always_filter` to False after instantiation to enable the default `is_noop` |
| 266 |
test. |
| 267 |
|
| 268 |
Override `is_noop` if you require a different test for your application. |
| 269 |
|
| 270 |
|
| 271 |
``TypedMultipleChoiceFilter`` |
| 272 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 273 |
|
| 274 |
Like ``MultipleChoiceFilter``, but in addition accepts the ``coerce`` parameter, as |
| 275 |
in ``TypedChoiceFilter``. |
| 276 |
|
| 277 |
|
| 278 |
``DateFilter`` |
| 279 |
~~~~~~~~~~~~~~ |
| 280 |
|
| 281 |
Matches on a date. Used with ``DateField`` by default. |
| 282 |
|
| 283 |
|
| 284 |
``TimeFilter`` |
| 285 |
~~~~~~~~~~~~~~ |
| 286 |
|
| 287 |
Matches on a time. Used with ``TimeField`` by default. |
| 288 |
|
| 289 |
|
| 290 |
``DateTimeFilter`` |
| 291 |
~~~~~~~~~~~~~~~~~~ |
| 292 |
|
| 293 |
Matches on a date and time. Used with ``DateTimeField`` by default. |
| 294 |
|
| 295 |
|
| 296 |
``IsoDateTimeFilter`` |
| 297 |
~~~~~~~~~~~~~~~~~~~~~ |
| 298 |
|
| 299 |
Uses ``IsoDateTimeField`` to support filtering on ISO 8601 formatted dates, as are often |
| 300 |
used in APIs, and are employed by default by Django REST Framework. |
| 301 |
|
| 302 |
Example:: |
| 303 |
|
| 304 |
class F(FilterSet): |
| 305 |
"""Filter for Books by date published, using ISO 8601 formatted dates""" |
| 306 |
published = IsoDateTimeFilter() |
| 307 |
|
| 308 |
class Meta: |
| 309 |
model = Book |
| 310 |
fields = ['published'] |
| 311 |
|
| 312 |
|
| 313 |
``DurationFilter`` |
| 314 |
~~~~~~~~~~~~~~~~~~ |
| 315 |
|
| 316 |
Matches on a duration. Used with ``DurationField`` by default. |
| 317 |
|
| 318 |
Supports both Django ('%d %H:%M:%S.%f') and ISO 8601 formatted durations (but |
| 319 |
only the sections that are accepted by Python's timedelta, so no year, month, |
| 320 |
and week designators, e.g. 'P3DT10H22M'). |
| 321 |
|
| 322 |
|
| 323 |
``ModelChoiceFilter`` |
| 324 |
~~~~~~~~~~~~~~~~~~~~~ |
| 325 |
|
| 326 |
Similar to a ``ChoiceFilter`` except it works with related models, used for |
| 327 |
``ForeignKey`` by default. |
| 328 |
|
| 329 |
If automatically instantiated, ``ModelChoiceFilter`` will use the default |
| 330 |
``QuerySet`` for the related field. If manually instantiated you **must** |
| 331 |
provide the ``queryset`` kwarg. |
| 332 |
|
| 333 |
Example:: |
| 334 |
|
| 335 |
class F(FilterSet): |
| 336 |
"""Filter for books by author""" |
| 337 |
author = ModelChoiceFilter(queryset=Author.objects.all()) |
| 338 |
|
| 339 |
class Meta: |
| 340 |
model = Book |
| 341 |
fields = ['author'] |
| 342 |
|
| 343 |
The ``queryset`` argument also supports callable behavior. If a callable is |
| 344 |
passed, it will be invoked with ``Filterset.request`` as its only argument. |
| 345 |
This allows you to easily filter by properties on the request object without |
| 346 |
having to override the ``FilterSet.__init__``. |
| 347 |
|
| 348 |
.. note:: |
| 349 |
|
| 350 |
You should expect that the `request` object may be `None`. |
| 351 |
|
| 352 |
.. code-block:: python |
| 353 |
|
| 354 |
def departments(request): |
| 355 |
if request is None: |
| 356 |
return Department.objects.none() |
| 357 |
|
| 358 |
company = request.user.company |
| 359 |
return company.department_set.all() |
| 360 |
|
| 361 |
class EmployeeFilter(filters.FilterSet): |
| 362 |
department = filters.ModelChoiceFilter(queryset=departments) |
| 363 |
... |
| 364 |
|
| 365 |
|
| 366 |
``ModelMultipleChoiceFilter`` |
| 367 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 368 |
|
| 369 |
Similar to a ``MultipleChoiceFilter`` except it works with related models, used |
| 370 |
for ``ManyToManyField`` by default. |
| 371 |
|
| 372 |
As with ``ModelChoiceFilter``, if automatically instantiated, |
| 373 |
``ModelMultipleChoiceFilter`` will use the default ``QuerySet`` for the related |
| 374 |
field. If manually instantiated you **must** provide the ``queryset`` kwarg. |
| 375 |
Like ``ModelChoiceFilter``, the ``queryset`` argument has callable behavior. |
| 376 |
|
| 377 |
To use a custom field name for the lookup, you can use ``to_field_name``:: |
| 378 |
|
| 379 |
class FooFilter(BaseFilterSet): |
| 380 |
foo = django_filters.filters.ModelMultipleChoiceFilter( |
| 381 |
field_name='attr__uuid', |
| 382 |
to_field_name='uuid', |
| 383 |
queryset=Foo.objects.all(), |
| 384 |
) |
| 385 |
|
| 386 |
If you want to use a custom queryset, e.g. to add annotated fields, this can be |
| 387 |
done as follows:: |
| 388 |
|
| 389 |
class MyMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter): |
| 390 |
def get_filter_predicate(self, v): |
| 391 |
return {'annotated_field': v.annotated_field} |
| 392 |
|
| 393 |
def filter(self, qs, value): |
| 394 |
if value: |
| 395 |
qs = qs.annotate_with_custom_field() |
| 396 |
qs = super().filter(qs, value) |
| 397 |
return qs |
| 398 |
|
| 399 |
foo = MyMultipleChoiceFilter( |
| 400 |
to_field_name='annotated_field', |
| 401 |
queryset=Model.objects.annotate_with_custom_field(), |
| 402 |
) |
| 403 |
|
| 404 |
The ``annotate_with_custom_field`` method would be defined through a custom |
| 405 |
QuerySet, which then gets used as the model's manager:: |
| 406 |
|
| 407 |
class CustomQuerySet(models.QuerySet): |
| 408 |
def annotate_with_custom_field(self): |
| 409 |
return self.annotate( |
| 410 |
custom_field=Case( |
| 411 |
When(foo__isnull=False, |
| 412 |
then=F('foo__uuid')), |
| 413 |
When(bar__isnull=False, |
| 414 |
then=F('bar__uuid')), |
| 415 |
default=None, |
| 416 |
), |
| 417 |
) |
| 418 |
|
| 419 |
class MyModel(models.Model): |
| 420 |
objects = CustomQuerySet.as_manager() |
| 421 |
|
| 422 |
|
| 423 |
``NumberFilter`` |
| 424 |
~~~~~~~~~~~~~~~~ |
| 425 |
|
| 426 |
Filters based on a numerical value, used with ``IntegerField``, ``FloatField``, |
| 427 |
and ``DecimalField`` by default. |
| 428 |
|
| 429 |
.. method:: NumberFilter.get_max_validator() |
| 430 |
|
| 431 |
Return a ``MaxValueValidator`` instance that will be added to |
| 432 |
``field.validators``. By default uses a limit value of ``1e50``. Return |
| 433 |
``None`` to disable maximum value validation. |
| 434 |
|
| 435 |
``NumericRangeFilter`` |
| 436 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 437 |
|
| 438 |
Filters where a value is between two numerical values, or greater than a minimum or less |
| 439 |
than a maximum where only one limit value is provided. This filter is designed to work |
| 440 |
with the Postgres Numerical Range Fields, including ``IntegerRangeField``, |
| 441 |
``BigIntegerRangeField`` and ``FloatRangeField`` (available since Django 1.8). The default |
| 442 |
widget used is the ``RangeField``. |
| 443 |
|
| 444 |
Regular field lookups are available in addition to several containment lookups, including |
| 445 |
``overlap``, ``contains``, and ``contained_by``. More details in the Django `docs`__. |
| 446 |
|
| 447 |
__ https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#querying-range-fields |
| 448 |
|
| 449 |
If the lower limit value is provided, the filter automatically defaults to ``startswith`` |
| 450 |
as the lookup and ``endswith`` if only the upper limit value is provided. |
| 451 |
|
| 452 |
``RangeFilter`` |
| 453 |
~~~~~~~~~~~~~~~ |
| 454 |
|
| 455 |
Filters where a value is between two numerical values, or greater than a minimum or less than a maximum where only one limit value is provided. :: |
| 456 |
|
| 457 |
class F(FilterSet): |
| 458 |
"""Filter for Books by Price""" |
| 459 |
price = RangeFilter() |
| 460 |
|
| 461 |
class Meta: |
| 462 |
model = Book |
| 463 |
fields = ['price'] |
| 464 |
|
| 465 |
qs = Book.objects.all().order_by('title') |
| 466 |
|
| 467 |
# Range: Books between 5€ and 15€ |
| 468 |
f = F({'price_min': '5', 'price_max': '15'}, queryset=qs) |
| 469 |
|
| 470 |
# Min-Only: Books costing more the 11€ |
| 471 |
f = F({'price_min': '11'}, queryset=qs) |
| 472 |
|
| 473 |
# Max-Only: Books costing less than 19€ |
| 474 |
f = F({'price_max': '19'}, queryset=qs) |
| 475 |
|
| 476 |
|
| 477 |
``DateRangeFilter`` |
| 478 |
~~~~~~~~~~~~~~~~~~~ |
| 479 |
|
| 480 |
Filter similar to the admin changelist date one, it has a number of common |
| 481 |
selections for working with date fields. |
| 482 |
|
| 483 |
``DateFromToRangeFilter`` |
| 484 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 485 |
|
| 486 |
Similar to a ``RangeFilter`` except it uses dates instead of numerical values. It can be used with ``DateField``. It also works with ``DateTimeField``, but takes into consideration only the date. |
| 487 |
|
| 488 |
Example of using the ``DateField`` field:: |
| 489 |
|
| 490 |
class Comment(models.Model): |
| 491 |
date = models.DateField() |
| 492 |
time = models.TimeField() |
| 493 |
|
| 494 |
class F(FilterSet): |
| 495 |
date = DateFromToRangeFilter() |
| 496 |
|
| 497 |
class Meta: |
| 498 |
model = Comment |
| 499 |
fields = ['date'] |
| 500 |
|
| 501 |
# Range: Comments added between 2016-01-01 and 2016-02-01 |
| 502 |
f = F({'date_after': '2016-01-01', 'date_before': '2016-02-01'}) |
| 503 |
|
| 504 |
# Min-Only: Comments added after 2016-01-01 |
| 505 |
f = F({'date_after': '2016-01-01'}) |
| 506 |
|
| 507 |
# Max-Only: Comments added before 2016-02-01 |
| 508 |
f = F({'date_before': '2016-02-01'}) |
| 509 |
|
| 510 |
.. note:: |
| 511 |
When filtering ranges that occurs on DST transition dates ``DateFromToRangeFilter`` will use the first valid hour of the day for start datetime and the last valid hour of the day for end datetime. |
| 512 |
This is OK for most applications, but if you want to customize this behavior you must extend ``DateFromToRangeFilter`` and make a custom field for it. |
| 513 |
|
| 514 |
.. warning:: |
| 515 |
If you're using Django prior to 1.9 you may hit ``AmbiguousTimeError`` or ``NonExistentTimeError`` when start/end date matches DST start/end respectively. |
| 516 |
This occurs because versions before 1.9 don't allow to change the DST behavior for making a datetime aware. |
| 517 |
|
| 518 |
Example of using the ``DateTimeField`` field:: |
| 519 |
|
| 520 |
class Article(models.Model): |
| 521 |
published = models.DateTimeField() |
| 522 |
|
| 523 |
class F(FilterSet): |
| 524 |
published = DateFromToRangeFilter() |
| 525 |
|
| 526 |
class Meta: |
| 527 |
model = Article |
| 528 |
fields = ['published'] |
| 529 |
|
| 530 |
Article.objects.create(published='2016-01-01 8:00') |
| 531 |
Article.objects.create(published='2016-01-20 10:00') |
| 532 |
Article.objects.create(published='2016-02-10 12:00') |
| 533 |
|
| 534 |
# Range: Articles published between 2016-01-01 and 2016-02-01 |
| 535 |
f = F({'published_after': '2016-01-01', 'published_before': '2016-02-01'}) |
| 536 |
assert len(f.qs) == 2 |
| 537 |
|
| 538 |
# Min-Only: Articles published after 2016-01-01 |
| 539 |
f = F({'published_after': '2016-01-01'}) |
| 540 |
assert len(f.qs) == 3 |
| 541 |
|
| 542 |
# Max-Only: Articles published before 2016-02-01 |
| 543 |
f = F({'published_before': '2016-02-01'}) |
| 544 |
assert len(f.qs) == 2 |
| 545 |
|
| 546 |
``DateTimeFromToRangeFilter`` |
| 547 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 548 |
|
| 549 |
Similar to a ``RangeFilter`` except it uses datetime format values instead of numerical values. It can be used with ``DateTimeField``. |
| 550 |
|
| 551 |
Example:: |
| 552 |
|
| 553 |
class Article(models.Model): |
| 554 |
published = models.DateTimeField() |
| 555 |
|
| 556 |
class F(FilterSet): |
| 557 |
published = DateTimeFromToRangeFilter() |
| 558 |
|
| 559 |
class Meta: |
| 560 |
model = Article |
| 561 |
fields = ['published'] |
| 562 |
|
| 563 |
Article.objects.create(published='2016-01-01 8:00') |
| 564 |
Article.objects.create(published='2016-01-01 9:30') |
| 565 |
Article.objects.create(published='2016-01-02 8:00') |
| 566 |
|
| 567 |
# Range: Articles published 2016-01-01 between 8:00 and 10:00 |
| 568 |
f = F({'published_after': '2016-01-01 8:00', 'published_before': '2016-01-01 10:00'}) |
| 569 |
assert len(f.qs) == 2 |
| 570 |
|
| 571 |
# Min-Only: Articles published after 2016-01-01 8:00 |
| 572 |
f = F({'published_after': '2016-01-01 8:00'}) |
| 573 |
assert len(f.qs) == 3 |
| 574 |
|
| 575 |
# Max-Only: Articles published before 2016-01-01 10:00 |
| 576 |
f = F({'published_before': '2016-01-01 10:00'}) |
| 577 |
assert len(f.qs) == 2 |
| 578 |
|
| 579 |
``IsoDateTimeFromToRangeFilter`` |
| 580 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 581 |
|
| 582 |
Similar to a ``RangeFilter`` except it uses ISO 8601 formatted values instead of numerical values. It can be used with ``IsoDateTimeField``. |
| 583 |
|
| 584 |
Example:: |
| 585 |
|
| 586 |
class Article(models.Model): |
| 587 |
published = django_filters.IsoDateTimeField() |
| 588 |
|
| 589 |
class F(FilterSet): |
| 590 |
published = IsoDateTimeFromToRangeFilter() |
| 591 |
|
| 592 |
class Meta: |
| 593 |
model = Article |
| 594 |
fields = ['published'] |
| 595 |
|
| 596 |
Article.objects.create(published='2016-01-01T8:00:00+01:00') |
| 597 |
Article.objects.create(published='2016-01-01T9:30:00+01:00') |
| 598 |
Article.objects.create(published='2016-01-02T8:00:00+01:00') |
| 599 |
|
| 600 |
# Range: Articles published 2016-01-01 between 8:00 and 10:00 |
| 601 |
f = F({'published_after': '2016-01-01T8:00:00+01:00', 'published_before': '2016-01-01T10:00:00+01:00'}) |
| 602 |
assert len(f.qs) == 2 |
| 603 |
|
| 604 |
# Min-Only: Articles published after 2016-01-01 8:00 |
| 605 |
f = F({'published_after': '2016-01-01T8:00:00+01:00'}) |
| 606 |
assert len(f.qs) == 3 |
| 607 |
|
| 608 |
# Max-Only: Articles published before 2016-01-01 10:00 |
| 609 |
f = F({'published_before': '2016-01-01T10:00:00+0100'}) |
| 610 |
assert len(f.qs) == 2 |
| 611 |
|
| 612 |
``TimeRangeFilter`` |
| 613 |
~~~~~~~~~~~~~~~~~~~ |
| 614 |
|
| 615 |
Similar to a ``RangeFilter`` except it uses time format values instead of numerical values. It can be used with ``TimeField``. |
| 616 |
|
| 617 |
Example:: |
| 618 |
|
| 619 |
class Comment(models.Model): |
| 620 |
date = models.DateField() |
| 621 |
time = models.TimeField() |
| 622 |
|
| 623 |
class F(FilterSet): |
| 624 |
time = TimeRangeFilter() |
| 625 |
|
| 626 |
class Meta: |
| 627 |
model = Comment |
| 628 |
fields = ['time'] |
| 629 |
|
| 630 |
# Range: Comments added between 8:00 and 10:00 |
| 631 |
f = F({'time_after': '8:00', 'time_before': '10:00'}) |
| 632 |
|
| 633 |
# Min-Only: Comments added after 8:00 |
| 634 |
f = F({'time_after': '8:00'}) |
| 635 |
|
| 636 |
# Max-Only: Comments added before 10:00 |
| 637 |
f = F({'time_before': '10:00'}) |
| 638 |
|
| 639 |
``AllValuesFilter`` |
| 640 |
~~~~~~~~~~~~~~~~~~~ |
| 641 |
|
| 642 |
This is a ``ChoiceFilter`` whose choices are the current values in the |
| 643 |
database. So if in the DB for the given field you have values of 5, 7, and 9 |
| 644 |
each of those is present as an option. This is similar to the default behavior |
| 645 |
of the admin. |
| 646 |
|
| 647 |
``AllValuesMultipleFilter`` |
| 648 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 649 |
|
| 650 |
This is a ``MultipleChoiceFilter`` whose choices are the current values in the |
| 651 |
database. So if in the DB for the given field you have values of 5, 7, and 9 |
| 652 |
each of those is present as an option. This is similar to the default behavior |
| 653 |
of the admin. |
| 654 |
|
| 655 |
.. _lookup-choice-filter: |
| 656 |
|
| 657 |
``LookupChoiceFilter`` |
| 658 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 659 |
|
| 660 |
A combined filter that allows users to select the lookup expression from a dropdown. |
| 661 |
|
| 662 |
* ``lookup_choices`` is an optional argument that accepts multiple input |
| 663 |
formats, and is ultimately normalized as the choices used in the lookup |
| 664 |
dropdown. See ``.get_lookup_choices()`` for more information. |
| 665 |
|
| 666 |
* ``field_class`` is an optional argument that allows you to set the inner |
| 667 |
form field class used to validate the value. Default: ``forms.CharField`` |
| 668 |
|
| 669 |
ex:: |
| 670 |
|
| 671 |
price = django_filters.LookupChoiceFilter( |
| 672 |
field_class=forms.DecimalField, |
| 673 |
lookup_choices=[ |
| 674 |
('exact', 'Equals'), |
| 675 |
('gt', 'Greater than'), |
| 676 |
('lt', 'Less than'), |
| 677 |
] |
| 678 |
) |
| 679 |
|
| 680 |
.. _base-in-filter: |
| 681 |
|
| 682 |
``BaseInFilter`` |
| 683 |
~~~~~~~~~~~~~~~~ |
| 684 |
|
| 685 |
This is a base class used for creating IN lookup filters. It is expected that |
| 686 |
this filter class is used in conjunction with another filter class, as this |
| 687 |
class **only** validates that the incoming value is comma-separated. The secondary |
| 688 |
filter is then used to validate the individual values. |
| 689 |
|
| 690 |
Example:: |
| 691 |
|
| 692 |
class NumberInFilter(BaseInFilter, NumberFilter): |
| 693 |
pass |
| 694 |
|
| 695 |
class F(FilterSet): |
| 696 |
id__in = NumberInFilter(field_name='id', lookup_expr='in') |
| 697 |
|
| 698 |
class Meta: |
| 699 |
model = User |
| 700 |
|
| 701 |
User.objects.create(username='alex') |
| 702 |
User.objects.create(username='jacob') |
| 703 |
User.objects.create(username='aaron') |
| 704 |
User.objects.create(username='carl') |
| 705 |
|
| 706 |
# In: User with IDs 1 and 3. |
| 707 |
f = F({'id__in': '1,3'}) |
| 708 |
assert len(f.qs) == 2 |
| 709 |
|
| 710 |
``BaseRangeFilter`` |
| 711 |
~~~~~~~~~~~~~~~~~~~ |
| 712 |
|
| 713 |
This is a base class used for creating RANGE lookup filters. It behaves |
| 714 |
identically to ``BaseInFilter`` with the exception that it expects only two |
| 715 |
comma-separated values. |
| 716 |
|
| 717 |
Example:: |
| 718 |
|
| 719 |
class NumberRangeFilter(BaseRangeFilter, NumberFilter): |
| 720 |
pass |
| 721 |
|
| 722 |
class F(FilterSet): |
| 723 |
id__range = NumberRangeFilter(field_name='id', lookup_expr='range') |
| 724 |
|
| 725 |
class Meta: |
| 726 |
model = User |
| 727 |
|
| 728 |
User.objects.create(username='alex') |
| 729 |
User.objects.create(username='jacob') |
| 730 |
User.objects.create(username='aaron') |
| 731 |
User.objects.create(username='carl') |
| 732 |
|
| 733 |
# Range: User with IDs between 1 and 3. |
| 734 |
f = F({'id__range': '1,3'}) |
| 735 |
assert len(f.qs) == 3 |
| 736 |
|
| 737 |
|
| 738 |
.. _ordering-filter: |
| 739 |
|
| 740 |
``OrderingFilter`` |
| 741 |
~~~~~~~~~~~~~~~~~~ |
| 742 |
|
| 743 |
Enable queryset ordering. As an extension of ``ChoiceFilter`` it accepts |
| 744 |
two additional arguments that are used to build the ordering choices. |
| 745 |
|
| 746 |
* ``fields`` is a mapping of {model field name: parameter name}. The |
| 747 |
parameter names are exposed in the choices and mask/alias the field |
| 748 |
names used in the ``order_by()`` call. Similar to field ``choices``, |
| 749 |
``fields`` accepts the 'list of two-tuples' syntax that retains order. |
| 750 |
``fields`` may also just be an iterable of strings. In this case, the |
| 751 |
field names simply double as the exposed parameter names. |
| 752 |
|
| 753 |
* ``field_labels`` is an optional argument that allows you to customize |
| 754 |
the display label for the corresponding parameter. It accepts a mapping |
| 755 |
of {field name: human readable label}. Keep in mind that the key is the |
| 756 |
field name, and not the exposed parameter name. |
| 757 |
|
| 758 |
.. code-block:: python |
| 759 |
|
| 760 |
class UserFilter(FilterSet): |
| 761 |
account = CharFilter(field_name='username') |
| 762 |
status = NumberFilter(field_name='status') |
| 763 |
|
| 764 |
o = OrderingFilter( |
| 765 |
# tuple-mapping retains order |
| 766 |
fields=( |
| 767 |
('username', 'account'), |
| 768 |
('first_name', 'first_name'), |
| 769 |
('last_name', 'last_name'), |
| 770 |
), |
| 771 |
|
| 772 |
# labels do not need to retain order |
| 773 |
field_labels={ |
| 774 |
'username': 'User account', |
| 775 |
} |
| 776 |
) |
| 777 |
|
| 778 |
class Meta: |
| 779 |
model = User |
| 780 |
fields = ['first_name', 'last_name'] |
| 781 |
|
| 782 |
>>> UserFilter().filters['o'].field.choices |
| 783 |
[ |
| 784 |
('account', 'User account'), |
| 785 |
('-account', 'User account (descending)'), |
| 786 |
('first_name', 'First name'), |
| 787 |
('-first_name', 'First name (descending)'), |
| 788 |
('last_name', 'Last name'), |
| 789 |
('-last_name', 'Last name (descending)'), |
| 790 |
] |
| 791 |
|
| 792 |
Additionally, you can just provide your own ``choices`` if you require |
| 793 |
explicit control over the exposed options. For example, when you might |
| 794 |
want to disable descending sort options. |
| 795 |
|
| 796 |
.. code-block:: python |
| 797 |
|
| 798 |
class UserFilter(FilterSet): |
| 799 |
account = CharFilter(field_name='username') |
| 800 |
status = NumberFilter(field_name='status') |
| 801 |
|
| 802 |
o = OrderingFilter( |
| 803 |
choices=( |
| 804 |
('account', 'Account'), |
| 805 |
), |
| 806 |
fields={ |
| 807 |
'username': 'account', |
| 808 |
}, |
| 809 |
) |
| 810 |
|
| 811 |
This filter is also CSV-based, and accepts multiple ordering params. The |
| 812 |
default select widget does not enable the use of this, but it is useful |
| 813 |
for APIs. ``SelectMultiple`` widgets are not compatible, given that they |
| 814 |
are not able to retain selection order. |
| 815 |
|
| 816 |
Adding Custom filter choices |
| 817 |
"""""""""""""""""""""""""""" |
| 818 |
|
| 819 |
If you wish to sort by non-model fields, you'll need to add custom handling to an |
| 820 |
``OrderingFilter`` subclass. For example, if you want to sort by a computed |
| 821 |
'relevance' factor, you would need to do something like the following: |
| 822 |
|
| 823 |
.. code-block:: python |
| 824 |
|
| 825 |
class CustomOrderingFilter(django_filters.OrderingFilter): |
| 826 |
|
| 827 |
def __init__(self, *args, **kwargs): |
| 828 |
super().__init__(*args, **kwargs) |
| 829 |
self.extra['choices'] += [ |
| 830 |
('relevance', 'Relevance'), |
| 831 |
('-relevance', 'Relevance (descending)'), |
| 832 |
] |
| 833 |
|
| 834 |
|
| 835 |
def filter(self, qs, value): |
| 836 |
# OrderingFilter is CSV-based, so `value` is a list |
| 837 |
if any(v in ['relevance', '-relevance'] for v in value): |
| 838 |
# sort queryset by relevance |
| 839 |
return ... |
| 840 |
|
| 841 |
return super().filter(qs, value) |