| 1 |
================== |
| 2 |
Tips and Solutions |
| 3 |
================== |
| 4 |
|
| 5 |
Common problems for declared filters |
| 6 |
------------------------------------ |
| 7 |
|
| 8 |
Below are some of the common problems that occur when declaring filters. It is |
| 9 |
recommended that you read this as it provides a more complete understanding of |
| 10 |
how filters work. |
| 11 |
|
| 12 |
|
| 13 |
Filter ``field_name`` and ``lookup_expr`` not configured |
| 14 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 15 |
|
| 16 |
While ``field_name`` and ``lookup_expr`` are optional, it is recommended that you specify |
| 17 |
them. By default, if ``field_name`` is not specified, the filter's name on the |
| 18 |
``FilterSet`` class will be used. Additionally, ``lookup_expr`` defaults to |
| 19 |
``exact``. The following is an example of a misconfigured price filter: |
| 20 |
|
| 21 |
.. code-block:: python |
| 22 |
|
| 23 |
class ProductFilter(django_filters.FilterSet): |
| 24 |
price__gt = django_filters.NumberFilter() |
| 25 |
|
| 26 |
The filter instance will have a field name of ``price__gt`` and an ``exact`` |
| 27 |
lookup type. Under the hood, this will incorrectly be resolved as: |
| 28 |
|
| 29 |
.. code-block:: python |
| 30 |
|
| 31 |
Product.objects.filter(price__gt__exact=value) |
| 32 |
|
| 33 |
The above will most likely generate a ``FieldError``. The correct configuration |
| 34 |
would be: |
| 35 |
|
| 36 |
.. code-block:: python |
| 37 |
|
| 38 |
class ProductFilter(django_filters.FilterSet): |
| 39 |
price__gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt') |
| 40 |
|
| 41 |
When using ``filterset_fields``, you can also add the ``lookup_expr`` in the |
| 42 |
dict of fields like so: |
| 43 |
|
| 44 |
.. code-block:: python |
| 45 |
|
| 46 |
# ... ModelViewSet with DjangoFilterBackend in filter_backends ... |
| 47 |
|
| 48 |
filterset_fields = { |
| 49 |
"price": ["gt", "exact"], |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
Missing ``lookup_expr`` for text search filters |
| 54 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 55 |
|
| 56 |
It's quite common to forget to set the lookup expression for :code:`CharField` |
| 57 |
and :code:`TextField` and wonder why a search for "foo" does not return results |
| 58 |
for "foobar". This is because the default lookup type is ``exact``, but you |
| 59 |
probably want to perform an ``icontains`` lookup. |
| 60 |
|
| 61 |
|
| 62 |
Filter and lookup expression mismatch (in, range, isnull) |
| 63 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 64 |
|
| 65 |
It's not always appropriate to directly match a filter to its model field's |
| 66 |
type, as some lookups expect different types of values. This is a commonly |
| 67 |
found issue with ``in``, ``range``, and ``isnull`` lookups. Let's look |
| 68 |
at the following product model: |
| 69 |
|
| 70 |
.. code-block:: python |
| 71 |
|
| 72 |
class Product(models.Model): |
| 73 |
category = models.ForeignKey(Category, null=True) |
| 74 |
|
| 75 |
Given that ``category`` is optional, it's reasonable to want to enable a search |
| 76 |
for uncategorized products. The following is an incorrectly configured |
| 77 |
``isnull`` filter: |
| 78 |
|
| 79 |
.. code-block:: python |
| 80 |
|
| 81 |
class ProductFilter(django_filters.FilterSet): |
| 82 |
uncategorized = django_filters.NumberFilter(field_name='category', lookup_expr='isnull') |
| 83 |
|
| 84 |
So what's the issue? While the underlying column type for ``category`` is an |
| 85 |
integer, ``isnull`` lookups expect a boolean value. A ``NumberFilter`` however |
| 86 |
only validates numbers. Filters are not `'expression aware'` and won't change |
| 87 |
behavior based on their ``lookup_expr``. You should use filters that match the |
| 88 |
data type of the lookup expression `instead` of the data type underlying the |
| 89 |
model field. The following would correctly allow you to search for both |
| 90 |
uncategorized products and products for a set of categories: |
| 91 |
|
| 92 |
.. code-block:: python |
| 93 |
|
| 94 |
class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter): |
| 95 |
pass |
| 96 |
|
| 97 |
class ProductFilter(django_filters.FilterSet): |
| 98 |
categories = NumberInFilter(field_name='category', lookup_expr='in') |
| 99 |
uncategorized = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull') |
| 100 |
|
| 101 |
More info on constructing ``in`` and ``range`` csv :ref:`filters <base-in-filter>`. |
| 102 |
|
| 103 |
|
| 104 |
Filtering by empty values |
| 105 |
------------------------- |
| 106 |
|
| 107 |
There are a number of cases where you may need to filter by empty or null |
| 108 |
values. The following are some common solutions to these problems: |
| 109 |
|
| 110 |
|
| 111 |
Filtering by null values |
| 112 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 113 |
|
| 114 |
As explained in the above "Filter and lookup expression mismatch" section, a |
| 115 |
common problem is how to correctly filter by null values on a field. |
| 116 |
|
| 117 |
Solution 1: Using a ``BooleanFilter`` with ``isnull`` |
| 118 |
""""""""""""""""""""""""""""""""""""""""""""""""""""" |
| 119 |
|
| 120 |
Using ``BooleanFilter`` with an ``isnull`` lookup is a builtin solution used by |
| 121 |
the FilterSet's automatic filter generation. To do this manually, simply add: |
| 122 |
|
| 123 |
.. code-block:: python |
| 124 |
|
| 125 |
class ProductFilter(django_filters.FilterSet): |
| 126 |
uncategorized = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull') |
| 127 |
|
| 128 |
.. note:: |
| 129 |
|
| 130 |
Remember that the filter class is validating the input value. The underlying |
| 131 |
type of the mode field is not relevant here. |
| 132 |
|
| 133 |
You may also reverse the logic with the ``exclude`` parameter. |
| 134 |
|
| 135 |
.. code-block:: python |
| 136 |
|
| 137 |
class ProductFilter(django_filters.FilterSet): |
| 138 |
has_category = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull', exclude=True) |
| 139 |
|
| 140 |
Solution 2: Using ``ChoiceFilter``'s null choice |
| 141 |
"""""""""""""""""""""""""""""""""""""""""""""""" |
| 142 |
|
| 143 |
If you're using a ChoiceFilter, you may also filter by null values by enabling |
| 144 |
the ``null_label`` parameter. More details in the ``ChoiceFilter`` reference |
| 145 |
:ref:`docs <choice-filter>`. |
| 146 |
|
| 147 |
.. code-block:: python |
| 148 |
|
| 149 |
class ProductFilter(django_filters.FilterSet): |
| 150 |
category = django_filters.ModelChoiceFilter( |
| 151 |
field_name='category', lookup_expr='isnull', |
| 152 |
null_label='Uncategorized', |
| 153 |
queryset=Category.objects.all(), |
| 154 |
) |
| 155 |
|
| 156 |
Solution 3: Combining fields w/ ``MultiValueField`` |
| 157 |
""""""""""""""""""""""""""""""""""""""""""""""""""" |
| 158 |
|
| 159 |
An alternative approach is to use Django's ``MultiValueField`` to manually add |
| 160 |
in a ``BooleanField`` to handle null values. Proof of concept: |
| 161 |
https://github.com/carltongibson/django-filter/issues/446 |
| 162 |
|
| 163 |
|
| 164 |
Filtering by an empty string |
| 165 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 166 |
|
| 167 |
It's not currently possible to filter by an empty string, since empty values are |
| 168 |
interpreted as a skipped filter. |
| 169 |
|
| 170 |
GET http://localhost/api/my-model?myfield= |
| 171 |
|
| 172 |
Solution 1: Magic values |
| 173 |
"""""""""""""""""""""""" |
| 174 |
|
| 175 |
You can override the ``filter()`` method of a filter class to specifically check |
| 176 |
for magic values. This is similar to the ``ChoiceFilter``'s null value handling. |
| 177 |
|
| 178 |
GET http://localhost/api/my-model?myfield=EMPTY |
| 179 |
|
| 180 |
.. code-block:: python |
| 181 |
|
| 182 |
class MyCharFilter(filters.CharFilter): |
| 183 |
empty_value = 'EMPTY' |
| 184 |
|
| 185 |
def filter(self, qs, value): |
| 186 |
if value != self.empty_value: |
| 187 |
return super().filter(qs, value) |
| 188 |
|
| 189 |
qs = self.get_method(qs)(**{'%s__%s' % (self.field_name, self.lookup_expr): ""}) |
| 190 |
return qs.distinct() if self.distinct else qs |
| 191 |
|
| 192 |
|
| 193 |
Solution 2: Empty string filter |
| 194 |
""""""""""""""""""""""""""""""" |
| 195 |
|
| 196 |
It would also be possible to create an empty value filter that exhibits the same |
| 197 |
behavior as an ``isnull`` filter. |
| 198 |
|
| 199 |
GET http://localhost/api/my-model?myfield__isempty=false |
| 200 |
|
| 201 |
.. code-block:: python |
| 202 |
|
| 203 |
from django.core.validators import EMPTY_VALUES |
| 204 |
|
| 205 |
class EmptyStringFilter(filters.BooleanFilter): |
| 206 |
def filter(self, qs, value): |
| 207 |
if value in EMPTY_VALUES: |
| 208 |
return qs |
| 209 |
|
| 210 |
exclude = self.exclude ^ (value is False) |
| 211 |
method = qs.exclude if exclude else qs.filter |
| 212 |
|
| 213 |
return method(**{self.field_name: ""}) |
| 214 |
|
| 215 |
|
| 216 |
class MyFilterSet(filters.FilterSet): |
| 217 |
myfield__isempty = EmptyStringFilter(field_name='myfield') |
| 218 |
|
| 219 |
class Meta: |
| 220 |
model = MyModel |
| 221 |
fields = [] |
| 222 |
|
| 223 |
|
| 224 |
Filtering by relative times |
| 225 |
--------------------------- |
| 226 |
|
| 227 |
Given a model with a timestamp field, it may be useful to filter based on relative times. |
| 228 |
For instance, perhaps we want to get data from the past *n* hours. |
| 229 |
This could be accomplished with a ``NumberFilter`` that invokes a custom method. |
| 230 |
|
| 231 |
.. code-block:: python |
| 232 |
|
| 233 |
from django.utils import timezone |
| 234 |
from datetime import timedelta |
| 235 |
... |
| 236 |
|
| 237 |
class DataModel(models.Model): |
| 238 |
time_stamp = models.DateTimeField() |
| 239 |
|
| 240 |
|
| 241 |
class DataFilter(django_filters.FilterSet): |
| 242 |
hours = django_filters.NumberFilter( |
| 243 |
field_name='time_stamp', method='get_past_n_hours', label="Past n hours") |
| 244 |
|
| 245 |
def get_past_n_hours(self, queryset, field_name, value): |
| 246 |
time_threshold = timezone.now() - timedelta(hours=int(value)) |
| 247 |
return queryset.filter(time_stamp__gte=time_threshold) |
| 248 |
|
| 249 |
class Meta: |
| 250 |
model = DataModel |
| 251 |
fields = ('hours',) |
| 252 |
|
| 253 |
Using ``initial`` values as defaults |
| 254 |
------------------------------------ |
| 255 |
|
| 256 |
In pre-1.0 versions of django-filter, a filter field's ``initial`` value was used as a |
| 257 |
default when no value was submitted. This behavior was not officially supported and has |
| 258 |
since been removed. |
| 259 |
|
| 260 |
|
| 261 |
.. warning:: It is recommended that you do **NOT** implement the below as it adversely |
| 262 |
affects usability. Django forms don't provide this behavior for a reason. |
| 263 |
|
| 264 |
- Using initial values as defaults is inconsistent with the behavior of Django forms. |
| 265 |
- Default values prevent users from filtering by empty values. |
| 266 |
- Default values prevent users from skipping that filter. |
| 267 |
|
| 268 |
If defaults are necessary though, the following should mimic the pre-1.0 behavior: |
| 269 |
|
| 270 |
.. code-block:: python |
| 271 |
|
| 272 |
class BaseFilterSet(FilterSet): |
| 273 |
|
| 274 |
def __init__(self, data=None, *args, **kwargs): |
| 275 |
# if filterset is bound, use initial values as defaults |
| 276 |
if data is not None: |
| 277 |
# get a mutable copy of the QueryDict |
| 278 |
data = data.copy() |
| 279 |
|
| 280 |
for name, f in self.base_filters.items(): |
| 281 |
initial = f.extra.get('initial') |
| 282 |
|
| 283 |
# filter param is either missing or empty, use initial as default |
| 284 |
if not data.get(name) and initial: |
| 285 |
data[name] = initial |
| 286 |
|
| 287 |
super().__init__(data, *args, **kwargs) |
| 288 |
|
| 289 |
|
| 290 |
Adding model field ``help_text`` to filters |
| 291 |
------------------------------------------- |
| 292 |
|
| 293 |
Model field ``help_text`` is not used by filters by default. It can be added |
| 294 |
using a simple FilterSet base class:: |
| 295 |
|
| 296 |
class HelpfulFilterSet(django_filters.FilterSet): |
| 297 |
@classmethod |
| 298 |
def filter_for_field(cls, f, name, lookup_expr): |
| 299 |
filter = super(HelpfulFilterSet, cls).filter_for_field(f, name, lookup_expr) |
| 300 |
filter.extra['help_text'] = f.help_text |
| 301 |
return filter |