File: filters.txt

package info (click to toggle)
django-filter 25.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,228 kB
  • sloc: python: 7,970; javascript: 7,213; makefile: 157; sh: 16
file content (841 lines) | stat: -rw-r--r-- 27,495 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
================
Filter Reference
================

This is a reference document with a list of the filters and their arguments.

.. _core-arguments:

Core Arguments
--------------

The following are the core arguments that apply to all filters. Note that they
are joined to construct the complete `lookup expression`_ that is the left hand
side of the ORM ``.filter()`` call.

.. _`lookup expression`: https://docs.djangoproject.com/en/stable/ref/models/lookups/#module-django.db.models.lookups

``field_name``
~~~~~~~~~~~~~~

The name of the model field that is filtered against. If this argument is not
provided, it defaults the filter's attribute name on the ``FilterSet`` class.
Field names can traverse relationships by joining the related parts with the ORM
lookup separator (``__``). e.g., a product's ``manufacturer__name``.

``lookup_expr``
~~~~~~~~~~~~~~~

The `field lookup`_ that should be performed in the filter call. Defaults to
``exact``. The ``lookup_expr`` can contain transforms if the expression parts
are joined by the ORM lookup separator (``__``). e.g., filter a datetime by its
year part ``year__gt``.

.. _`Field lookup`: https://docs.djangoproject.com/en/stable/ref/models/querysets/#field-lookups

.. _keyword-only-arguments:

Keyword-only Arguments
----------------------

The following are optional arguments that can be used to modify the behavior of
all filters.

``label``
~~~~~~~~~

The label as it will appear in the HTML, analogous to a form field's label
argument. If a label is not provided, a verbose label will be generated based
on the field ``field_name`` and the parts of the ``lookup_expr``
(see: :ref:`verbose-lookups-setting`).

.. _filter-method:

``method``
~~~~~~~~~~

An optional argument that tells the filter how to handle the queryset. It can
accept either a callable or the name of a method on the ``FilterSet``. The
callable receives a ``QuerySet``, the name of the model field to filter on, and
the value to filter with. It should return a filtered ``Queryset``.

Note that the value is validated by the ``Filter.field``, so raw value
transformation and empty value checking should be unnecessary.

.. code-block:: python

    class F(FilterSet):
        """Filter for Books by if books are published or not"""
        published = BooleanFilter(field_name='published_on', method='filter_published')

        def filter_published(self, queryset, name, value):
            # construct the full lookup expression.
            lookup = '__'.join([name, 'isnull'])
            return queryset.filter(**{lookup: False})

            # alternatively, you could opt to hardcode the lookup. e.g.,
            # return queryset.filter(published_on__isnull=False)

        class Meta:
            model = Book
            fields = ['published']


    # Callables may also be defined out of the class scope.
    def filter_not_empty(queryset, name, value):
        lookup = '__'.join([name, 'isnull'])
        return queryset.filter(**{lookup: False})

    class F(FilterSet):
        """Filter for Books by if books are published or not"""
        published = BooleanFilter(field_name='published_on', method=filter_not_empty)

        class Meta:
            model = Book
            fields = ['published']


``distinct``
~~~~~~~~~~~~

A boolean that specifies whether the Filter will use distinct on the queryset.
This option can be used to eliminate duplicate results when using filters that
span relationships. Defaults to ``False``.

``exclude``
~~~~~~~~~~~

A boolean that specifies whether the Filter should use ``filter`` or ``exclude``
on the queryset. Defaults to ``False``.

``required``
~~~~~~~~~~~~

A boolean that specifies whether the Filter is required or not. Defaults to ``False``.


``**kwargs``
~~~~~~~~~~~~

Any additional keyword arguments are stored as the ``extra`` parameter on the
filter. They are provided to the accompanying form ``Field`` and can be used to
provide arguments like ``choices``. Some field-related arguments:

``widget``
""""""""""

The django.form Widget class which will represent the ``Filter``.  In addition
to the widgets that are included with Django that you can use there are
additional ones that django-filter provides which may be useful:

    * :ref:`LinkWidget <link-widget>` -- this displays the options in a manner
      similar to the way the Django Admin does, as a series of links. The link
      for the selected option will have ``class="selected"``.
    * :ref:`BooleanWidget <boolean-widget>` -- this widget converts its input
      into Python's True/False values. It will convert all case variations of
      ``True`` and ``False`` into the internal Python values.
    * :ref:`CSVWidget <csv-widget>` -- this widget expects a comma separated
      value and converts it into a list of string values. It is expected that
      the field class handle a list of values as well as type conversion.
    * :ref:`RangeWidget <range-widget>` -- this widget is used with ``RangeFilter``
      to generate two form input elements using a single field.


ModelChoiceFilter and ModelMultipleChoiceFilter arguments
---------------------------------------------------------

These arguments apply specifically to ModelChoiceFilter and
ModelMultipleChoiceFilter only.

``queryset``
~~~~~~~~~~~~

``ModelChoiceFilter`` and ``ModelMultipleChoiceFilter`` require a queryset to
operate on which must be passed as a kwarg.

``to_field_name``
~~~~~~~~~~~~~~~~~

If you pass in ``to_field_name`` (which gets forwarded to the Django field),
it will be used also in the default ``get_filter_predicate`` implementation
as the model's attribute.


Filters
-------

``CharFilter``
~~~~~~~~~~~~~~

This filter does simple character matches, used with ``CharField`` and
``TextField`` by default.

``UUIDFilter``
~~~~~~~~~~~~~~

This filter matches UUID values, used with ``models.UUIDField`` by default.

``BooleanFilter``
~~~~~~~~~~~~~~~~~

This filter matches a boolean, either ``True`` or ``False``, used with
``BooleanField`` and ``NullBooleanField`` by default.

.. _choice-filter:

``ChoiceFilter``
~~~~~~~~~~~~~~~~

This filter matches values in its ``choices`` argument. The ``choices`` must be
explicitly passed when the filter is declared on the ``FilterSet``. For example,

.. code-block:: python

    class User(models.Model):
        username = models.CharField(max_length=255)
        first_name = SubCharField(max_length=100)
        last_name = SubSubCharField(max_length=100)

        status = models.IntegerField(choices=STATUS_CHOICES, default=0)

    STATUS_CHOICES = (
        (0, 'Regular'),
        (1, 'Manager'),
        (2, 'Admin'),
    )

    class F(FilterSet):
        status = ChoiceFilter(choices=STATUS_CHOICES)
        class Meta:
            model = User
            fields = ['status']


``ChoiceFilter`` also has arguments that enable a choice for not filtering, as
well as a choice for filtering by ``None`` values. Each of the arguments have a
corresponding global setting (:doc:`/ref/settings`).

* ``empty_label``: The display label to use for the select choice to not filter.
  The choice may be disabled by setting this argument to ``None``. Defaults to
  ``FILTERS_EMPTY_CHOICE_LABEL``.
* ``null_label``: The display label to use for the choice to filter by ``None``
  values. The choice may be disabled by setting this argument to ``None``.
  Defaults to ``FILTERS_NULL_CHOICE_LABEL``.
* ``null_value``: The special value to match to enable filtering by ``None``
  values. This value defaults ``FILTERS_NULL_CHOICE_VALUE`` and needs to be
  a non-empty value (``''``, ``None``, ``[]``, ``()``, ``{}``).


``TypedChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~

The same as ``ChoiceFilter`` with the added possibility to convert value to
match against. This could be done by using `coerce` parameter.
An example use-case is limiting boolean choices to match against so only
some predefined strings could be used as input of a boolean filter::

    import django_filters
    from distutils.util import strtobool

    BOOLEAN_CHOICES = (('false', 'False'), ('true', 'True'),)

    class YourFilterSet(django_filters.FilterSet):
        ...
        flag = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES,
                                                coerce=strtobool)


``MultipleChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~~~~

The same as ``ChoiceFilter`` except the user can select multiple choices
and the filter will form the OR of these choices by default to match items.
The filter will form the AND of the selected choices when the ``conjoined=True``
argument is passed to this class.

Multiple choices are represented in the query string by reusing the same key with
different values (e.g. ''?status=Regular&status=Admin'').

``distinct`` defaults to ``True`` as to-many relationships will generally require this.

Advanced Use: Depending on your application logic, when all or no choices are
selected, filtering may be a noop. In this case you may wish to avoid the
filtering overhead, particularly of the `distinct` call.

Set `always_filter` to False after instantiation to enable the default `is_noop`
test.

Override `is_noop` if you require a different test for your application.


``TypedMultipleChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Like ``MultipleChoiceFilter``, but in addition accepts the ``coerce`` parameter, as
in ``TypedChoiceFilter``.


``DateFilter``
~~~~~~~~~~~~~~

Matches on a date.  Used with ``DateField`` by default.


``TimeFilter``
~~~~~~~~~~~~~~

Matches on a time.  Used with ``TimeField`` by default.


``DateTimeFilter``
~~~~~~~~~~~~~~~~~~

Matches on a date and time.  Used with ``DateTimeField`` by default.


``IsoDateTimeFilter``
~~~~~~~~~~~~~~~~~~~~~

Uses ``IsoDateTimeField`` to support filtering on ISO 8601 formatted dates, as are often
used in APIs, and are employed by default by Django REST Framework.

Example::

    class F(FilterSet):
        """Filter for Books by date published, using ISO 8601 formatted dates"""
        published = IsoDateTimeFilter()

        class Meta:
            model = Book
            fields = ['published']


``DurationFilter``
~~~~~~~~~~~~~~~~~~

Matches on a duration.  Used with ``DurationField`` by default.

Supports both Django ('%d %H:%M:%S.%f') and ISO 8601 formatted durations (but
only the sections that are accepted by Python's timedelta, so no year, month,
and week designators, e.g. 'P3DT10H22M').


``ModelChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~

Similar to a ``ChoiceFilter`` except it works with related models, used for
``ForeignKey`` by default.

If automatically instantiated, ``ModelChoiceFilter`` will use the default
``QuerySet`` for the related field. If manually instantiated you **must**
provide the ``queryset`` kwarg.

Example::

    class F(FilterSet):
        """Filter for books by author"""
        author = ModelChoiceFilter(queryset=Author.objects.all())

        class Meta:
            model = Book
            fields = ['author']

The ``queryset`` argument also supports callable behavior. If a callable is
passed, it will be invoked with ``Filterset.request`` as its only argument.
This allows you to easily filter by properties on the request object without
having to override the ``FilterSet.__init__``.

.. note::

    You should expect that the `request` object may be `None`.

.. code-block:: python

    def departments(request):
        if request is None:
            return Department.objects.none()

        company = request.user.company
        return company.department_set.all()

    class EmployeeFilter(filters.FilterSet):
        department = filters.ModelChoiceFilter(queryset=departments)
        ...


``ModelMultipleChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Similar to a ``MultipleChoiceFilter`` except it works with related models, used
for ``ManyToManyField`` by default.

As with ``ModelChoiceFilter``, if automatically instantiated,
``ModelMultipleChoiceFilter`` will use the default ``QuerySet`` for the related
field. If manually instantiated you **must** provide the ``queryset`` kwarg.
Like ``ModelChoiceFilter``, the ``queryset`` argument has callable behavior.

To use a custom field name for the lookup, you can use ``to_field_name``::

    class FooFilter(BaseFilterSet):
        foo = django_filters.filters.ModelMultipleChoiceFilter(
            field_name='attr__uuid',
            to_field_name='uuid',
            queryset=Foo.objects.all(),
        )

If you want to use a custom queryset, e.g. to add annotated fields, this can be
done as follows::

    class MyMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter):
        def get_filter_predicate(self, v):
            return {'annotated_field': v.annotated_field}

        def filter(self, qs, value):
            if value:
                qs = qs.annotate_with_custom_field()
                qs = super().filter(qs, value)
            return qs

    foo = MyMultipleChoiceFilter(
        to_field_name='annotated_field',
        queryset=Model.objects.annotate_with_custom_field(),
    )

The ``annotate_with_custom_field`` method would be defined through a custom
QuerySet, which then gets used as the model's manager::

    class CustomQuerySet(models.QuerySet):
        def annotate_with_custom_field(self):
            return self.annotate(
                custom_field=Case(
                    When(foo__isnull=False,
                         then=F('foo__uuid')),
                    When(bar__isnull=False,
                         then=F('bar__uuid')),
                    default=None,
                ),
            )

    class MyModel(models.Model):
        objects = CustomQuerySet.as_manager()


``NumberFilter``
~~~~~~~~~~~~~~~~

Filters based on a numerical value, used with ``IntegerField``, ``FloatField``,
and ``DecimalField`` by default.

.. method:: NumberFilter.get_max_validator()

    Return a ``MaxValueValidator`` instance that will be added to
    ``field.validators``. By default uses a limit value of ``1e50``. Return
    ``None`` to disable maximum value validation.

``NumericRangeFilter``
~~~~~~~~~~~~~~~~~~~~~~

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. This filter is designed to work
with the Postgres Numerical Range Fields, including ``IntegerRangeField``,
``BigIntegerRangeField`` and ``FloatRangeField`` (available since Django 1.8). The default
widget used is the ``RangeField``.

Regular field lookups are available in addition to several containment lookups, including
``overlap``, ``contains``, and ``contained_by``. More details in the Django `docs`__.

__ https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#querying-range-fields

If the lower limit value is provided, the filter automatically defaults to ``startswith``
as the lookup and ``endswith`` if only the upper limit value is provided.

``RangeFilter``
~~~~~~~~~~~~~~~

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. ::

    class F(FilterSet):
        """Filter for Books by Price"""
        price = RangeFilter()

        class Meta:
            model = Book
            fields = ['price']

    qs = Book.objects.all().order_by('title')

    # Range: Books between 5€ and 15€
    f = F({'price_min': '5', 'price_max': '15'}, queryset=qs)

    # Min-Only: Books costing more the 11€
    f = F({'price_min': '11'}, queryset=qs)

    # Max-Only: Books costing less than 19€
    f = F({'price_max': '19'}, queryset=qs)


``DateRangeFilter``
~~~~~~~~~~~~~~~~~~~

Filter similar to the admin changelist date one, it has a number of common
selections for working with date fields.

``DateFromToRangeFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~

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.

Example of using the ``DateField`` field::

    class Comment(models.Model):
        date = models.DateField()
        time = models.TimeField()

    class F(FilterSet):
        date = DateFromToRangeFilter()

        class Meta:
            model = Comment
            fields = ['date']

    # Range: Comments added between 2016-01-01 and 2016-02-01
    f = F({'date_after': '2016-01-01', 'date_before': '2016-02-01'})

    # Min-Only: Comments added after 2016-01-01
    f = F({'date_after': '2016-01-01'})

    # Max-Only: Comments added before 2016-02-01
    f = F({'date_before': '2016-02-01'})

.. note::
    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.
    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.

.. warning::
    If you're using Django prior to 1.9 you may hit ``AmbiguousTimeError`` or ``NonExistentTimeError`` when start/end date matches DST start/end respectively.
    This occurs because versions before 1.9 don't allow to change the DST behavior for making a datetime aware.

Example of using the ``DateTimeField`` field::

    class Article(models.Model):
        published = models.DateTimeField()

    class F(FilterSet):
        published = DateFromToRangeFilter()

        class Meta:
            model = Article
            fields = ['published']

    Article.objects.create(published='2016-01-01 8:00')
    Article.objects.create(published='2016-01-20 10:00')
    Article.objects.create(published='2016-02-10 12:00')

    # Range: Articles published between 2016-01-01 and 2016-02-01
    f = F({'published_after': '2016-01-01', 'published_before': '2016-02-01'})
    assert len(f.qs) == 2

    # Min-Only: Articles published after 2016-01-01
    f = F({'published_after': '2016-01-01'})
    assert len(f.qs) == 3

    # Max-Only: Articles published before 2016-02-01
    f = F({'published_before': '2016-02-01'})
    assert len(f.qs) == 2

``DateTimeFromToRangeFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Similar to a ``RangeFilter`` except it uses datetime format values instead of numerical values. It can be used with ``DateTimeField``.

Example::

    class Article(models.Model):
        published = models.DateTimeField()

    class F(FilterSet):
        published = DateTimeFromToRangeFilter()

        class Meta:
            model = Article
            fields = ['published']

    Article.objects.create(published='2016-01-01 8:00')
    Article.objects.create(published='2016-01-01 9:30')
    Article.objects.create(published='2016-01-02 8:00')

    # Range: Articles published 2016-01-01 between 8:00 and 10:00
    f = F({'published_after': '2016-01-01 8:00', 'published_before': '2016-01-01 10:00'})
    assert len(f.qs) == 2

    # Min-Only: Articles published after 2016-01-01 8:00
    f = F({'published_after': '2016-01-01 8:00'})
    assert len(f.qs) == 3

    # Max-Only: Articles published before 2016-01-01 10:00
    f = F({'published_before': '2016-01-01 10:00'})
    assert len(f.qs) == 2

``IsoDateTimeFromToRangeFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Similar to a ``RangeFilter`` except it uses ISO 8601 formatted values instead of numerical values. It can be used with ``IsoDateTimeField``.

Example::

    class Article(models.Model):
        published = django_filters.IsoDateTimeField()

    class F(FilterSet):
        published = IsoDateTimeFromToRangeFilter()

        class Meta:
            model = Article
            fields = ['published']

    Article.objects.create(published='2016-01-01T8:00:00+01:00')
    Article.objects.create(published='2016-01-01T9:30:00+01:00')
    Article.objects.create(published='2016-01-02T8:00:00+01:00')

    # Range: Articles published 2016-01-01 between 8:00 and 10:00
    f = F({'published_after': '2016-01-01T8:00:00+01:00', 'published_before': '2016-01-01T10:00:00+01:00'})
    assert len(f.qs) == 2

    # Min-Only: Articles published after 2016-01-01 8:00
    f = F({'published_after': '2016-01-01T8:00:00+01:00'})
    assert len(f.qs) == 3

    # Max-Only: Articles published before 2016-01-01 10:00
    f = F({'published_before': '2016-01-01T10:00:00+0100'})
    assert len(f.qs) == 2

``TimeRangeFilter``
~~~~~~~~~~~~~~~~~~~

Similar to a ``RangeFilter`` except it uses time format values instead of numerical values. It can be used with ``TimeField``.

Example::

    class Comment(models.Model):
        date = models.DateField()
        time = models.TimeField()

    class F(FilterSet):
        time = TimeRangeFilter()

        class Meta:
            model = Comment
            fields = ['time']

    # Range: Comments added between 8:00 and 10:00
    f = F({'time_after': '8:00', 'time_before': '10:00'})

    # Min-Only: Comments added after 8:00
    f = F({'time_after': '8:00'})

    # Max-Only: Comments added before 10:00
    f = F({'time_before': '10:00'})

``AllValuesFilter``
~~~~~~~~~~~~~~~~~~~

This is a ``ChoiceFilter`` whose choices are the current values in the
database.  So if in the DB for the given field you have values of 5, 7, and 9
each of those is present as an option.  This is similar to the default behavior
of the admin.

``AllValuesMultipleFilter``
~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is a ``MultipleChoiceFilter`` whose choices are the current values in the
database.  So if in the DB for the given field you have values of 5, 7, and 9
each of those is present as an option.  This is similar to the default behavior
of the admin.

.. _lookup-choice-filter:

``LookupChoiceFilter``
~~~~~~~~~~~~~~~~~~~~~~

A combined filter that allows users to select the lookup expression from a dropdown.

* ``lookup_choices`` is an optional argument that accepts multiple input
  formats, and is ultimately normalized as the choices used in the lookup
  dropdown. See ``.get_lookup_choices()`` for more information.

* ``field_class`` is an optional argument that allows you to set the inner
  form field class used to validate the value. Default: ``forms.CharField``

ex::

    price = django_filters.LookupChoiceFilter(
        field_class=forms.DecimalField,
        lookup_choices=[
            ('exact', 'Equals'),
            ('gt', 'Greater than'),
            ('lt', 'Less than'),
        ]
    )

.. _base-in-filter:

``BaseInFilter``
~~~~~~~~~~~~~~~~

This is a base class used for creating IN lookup filters. It is expected that
this filter class is used in conjunction with another filter class, as this
class **only** validates that the incoming value is comma-separated. The secondary
filter is then used to validate the individual values.

Example::

    class NumberInFilter(BaseInFilter, NumberFilter):
        pass

    class F(FilterSet):
        id__in = NumberInFilter(field_name='id', lookup_expr='in')

        class Meta:
            model = User

    User.objects.create(username='alex')
    User.objects.create(username='jacob')
    User.objects.create(username='aaron')
    User.objects.create(username='carl')

    # In: User with IDs 1 and 3.
    f = F({'id__in': '1,3'})
    assert len(f.qs) == 2

``BaseRangeFilter``
~~~~~~~~~~~~~~~~~~~

This is a base class used for creating RANGE lookup filters. It behaves
identically to ``BaseInFilter`` with the exception that it expects only two
comma-separated values.

Example::

    class NumberRangeFilter(BaseRangeFilter, NumberFilter):
        pass

    class F(FilterSet):
        id__range = NumberRangeFilter(field_name='id', lookup_expr='range')

        class Meta:
            model = User

    User.objects.create(username='alex')
    User.objects.create(username='jacob')
    User.objects.create(username='aaron')
    User.objects.create(username='carl')

    # Range: User with IDs between 1 and 3.
    f = F({'id__range': '1,3'})
    assert len(f.qs) == 3


.. _ordering-filter:

``OrderingFilter``
~~~~~~~~~~~~~~~~~~

Enable queryset ordering. As an extension of ``ChoiceFilter`` it accepts
two additional arguments that are used to build the ordering choices.

* ``fields`` is a mapping of {model field name: parameter name}. The
  parameter names are exposed in the choices and mask/alias the field
  names used in the ``order_by()`` call. Similar to field ``choices``,
  ``fields`` accepts the 'list of two-tuples' syntax that retains order.
  ``fields`` may also just be an iterable of strings. In this case, the
  field names simply double as the exposed parameter names.

* ``field_labels`` is an optional argument that allows you to customize
  the display label for the corresponding parameter. It accepts a mapping
  of {field name: human readable label}. Keep in mind that the key is the
  field name, and not the exposed parameter name.

.. code-block:: python

    class UserFilter(FilterSet):
        account = CharFilter(field_name='username')
        status = NumberFilter(field_name='status')

        o = OrderingFilter(
            # tuple-mapping retains order
            fields=(
                ('username', 'account'),
                ('first_name', 'first_name'),
                ('last_name', 'last_name'),
            ),

            # labels do not need to retain order
            field_labels={
                'username': 'User account',
            }
        )

        class Meta:
            model = User
            fields = ['first_name', 'last_name']

    >>> UserFilter().filters['o'].field.choices
    [
        ('account', 'User account'),
        ('-account', 'User account (descending)'),
        ('first_name', 'First name'),
        ('-first_name', 'First name (descending)'),
        ('last_name', 'Last name'),
        ('-last_name', 'Last name (descending)'),
    ]

Additionally, you can just provide your own ``choices`` if you require
explicit control over the exposed options. For example, when you might
want to disable descending sort options.

.. code-block:: python

    class UserFilter(FilterSet):
        account = CharFilter(field_name='username')
        status = NumberFilter(field_name='status')

        o = OrderingFilter(
            choices=(
                ('account', 'Account'),
            ),
            fields={
                'username': 'account',
            },
        )

This filter is also CSV-based, and accepts multiple ordering params. The
default select widget does not enable the use of this, but it is useful
for APIs. ``SelectMultiple`` widgets are not compatible, given that they
are not able to retain selection order.

Adding Custom filter choices
""""""""""""""""""""""""""""

If you wish to sort by non-model fields, you'll need to add custom handling to an
``OrderingFilter`` subclass. For example, if you want to sort by a computed
'relevance' factor, you would need to do something like the following:

.. code-block:: python

    class CustomOrderingFilter(django_filters.OrderingFilter):

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.extra['choices'] += [
                ('relevance', 'Relevance'),
                ('-relevance', 'Relevance (descending)'),
            ]


        def filter(self, qs, value):
            # OrderingFilter is CSV-based, so `value` is a list
            if any(v in ['relevance', '-relevance'] for v in value):
                # sort queryset by relevance
                return ...

            return super().filter(qs, value)