| 1 |
=============== |
| 2 |
Getting Started |
| 3 |
=============== |
| 4 |
|
| 5 |
Django-filter provides a simple way to filter down a queryset based on |
| 6 |
parameters a user provides. Say we have a ``Product`` model and we want to let |
| 7 |
our users filter which products they see on a list page. |
| 8 |
|
| 9 |
.. note:: |
| 10 |
|
| 11 |
If you're using django-filter with Django Rest Framework, it's recommended |
| 12 |
that you read the :ref:`drf integration` docs after this guide. |
| 13 |
|
| 14 |
The model |
| 15 |
--------- |
| 16 |
|
| 17 |
Let's start with our model:: |
| 18 |
|
| 19 |
from django.db import models |
| 20 |
|
| 21 |
class Product(models.Model): |
| 22 |
name = models.CharField(max_length=255) |
| 23 |
price = models.DecimalField(max_digits=5, decimal_places=2) |
| 24 |
description = models.TextField() |
| 25 |
release_date = models.DateField() |
| 26 |
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) |
| 27 |
|
| 28 |
The filter |
| 29 |
---------- |
| 30 |
|
| 31 |
We have a number of fields and we want to let our users filter based on the |
| 32 |
name, the price or the release_date. We create a ``FilterSet`` for this:: |
| 33 |
|
| 34 |
import django_filters |
| 35 |
|
| 36 |
class ProductFilter(django_filters.FilterSet): |
| 37 |
name = django_filters.CharFilter(lookup_expr='iexact') |
| 38 |
|
| 39 |
class Meta: |
| 40 |
model = Product |
| 41 |
fields = ['price', 'release_date'] |
| 42 |
|
| 43 |
|
| 44 |
As you can see this uses a very similar API to Django's ``ModelForm``. Just |
| 45 |
like with a ``ModelForm`` we can also override filters, or add new ones using a |
| 46 |
declarative syntax. |
| 47 |
|
| 48 |
Declaring filters |
| 49 |
~~~~~~~~~~~~~~~~~ |
| 50 |
|
| 51 |
The declarative syntax provides you with the most flexibility when creating |
| 52 |
filters, however it is fairly verbose. We'll use the below example to outline |
| 53 |
the :ref:`core filter arguments <core-arguments>` on a ``FilterSet``:: |
| 54 |
|
| 55 |
class ProductFilter(django_filters.FilterSet): |
| 56 |
price = django_filters.NumberFilter() |
| 57 |
price__gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt') |
| 58 |
price__lt = django_filters.NumberFilter(field_name='price', lookup_expr='lt') |
| 59 |
|
| 60 |
release_year = django_filters.NumberFilter(field_name='release_date', lookup_expr='year') |
| 61 |
release_year__gt = django_filters.NumberFilter(field_name='release_date', lookup_expr='year__gt') |
| 62 |
release_year__lt = django_filters.NumberFilter(field_name='release_date', lookup_expr='year__lt') |
| 63 |
|
| 64 |
manufacturer__name = django_filters.CharFilter(lookup_expr='icontains') |
| 65 |
|
| 66 |
class Meta: |
| 67 |
model = Product |
| 68 |
fields = ['price', 'release_date', 'manufacturer'] |
| 69 |
|
| 70 |
There are two main arguments for filters: |
| 71 |
|
| 72 |
- ``field_name``: The name of the model field to filter on. You can traverse |
| 73 |
"relationship paths" using Django's ``__`` syntax to filter fields on a |
| 74 |
related model. ex, ``manufacturer__name``. |
| 75 |
- ``lookup_expr``: The `field lookup`_ to use when filtering. Django's ``__`` |
| 76 |
syntax can again be used in order to support lookup transforms. |
| 77 |
ex, ``year__gte``. |
| 78 |
|
| 79 |
.. _`field lookup`: https://docs.djangoproject.com/en/stable/ref/models/querysets/#field-lookups |
| 80 |
|
| 81 |
Together, the field ``field_name`` and ``lookup_expr`` represent a complete Django |
| 82 |
lookup expression. A detailed explanation of lookup expressions is provided in |
| 83 |
Django's `lookup reference`_. django-filter supports expressions containing |
| 84 |
both transforms and a final lookup. |
| 85 |
|
| 86 |
.. _`lookup reference`: https://docs.djangoproject.com/en/stable/ref/models/lookups/#module-django.db.models.lookups |
| 87 |
|
| 88 |
|
| 89 |
Generating filters with Meta.fields |
| 90 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 91 |
|
| 92 |
The FilterSet Meta class provides a ``fields`` attribute that can be used for |
| 93 |
easily specifying multiple filters without significant code duplication. The |
| 94 |
base syntax supports a list of multiple field names:: |
| 95 |
|
| 96 |
import django_filters |
| 97 |
|
| 98 |
class ProductFilter(django_filters.FilterSet): |
| 99 |
class Meta: |
| 100 |
model = Product |
| 101 |
fields = ['price', 'release_date'] |
| 102 |
|
| 103 |
The above generates 'exact' lookups for both the 'price' and 'release_date' |
| 104 |
fields. |
| 105 |
|
| 106 |
Additionally, a dictionary can be used to specify multiple lookup expressions |
| 107 |
for each field:: |
| 108 |
|
| 109 |
import django_filters |
| 110 |
|
| 111 |
class ProductFilter(django_filters.FilterSet): |
| 112 |
class Meta: |
| 113 |
model = Product |
| 114 |
fields = { |
| 115 |
'price': ['lt', 'gt'], |
| 116 |
'release_date': ['exact', 'year__gt'], |
| 117 |
} |
| 118 |
|
| 119 |
The above would generate 'price__lt', 'price__gt', 'release_date', and |
| 120 |
'release_date__year__gt' filters. |
| 121 |
|
| 122 |
.. note:: |
| 123 |
|
| 124 |
The filter lookup type 'exact' is an implicit default and therefore never |
| 125 |
added to a filter name. In the above example, the release date's exact |
| 126 |
filter is 'release_date', not 'release_date__exact'. This can be overridden |
| 127 |
by the FILTERS_DEFAULT_LOOKUP_EXPR setting. |
| 128 |
|
| 129 |
Items in the ``fields`` sequence in the ``Meta`` class may include |
| 130 |
"relationship paths" using Django's ``__`` syntax to filter on fields on a |
| 131 |
related model:: |
| 132 |
|
| 133 |
class ProductFilter(django_filters.FilterSet): |
| 134 |
class Meta: |
| 135 |
model = Product |
| 136 |
fields = ['manufacturer__country'] |
| 137 |
|
| 138 |
|
| 139 |
Overriding default filters |
| 140 |
"""""""""""""""""""""""""" |
| 141 |
|
| 142 |
Like ``django.contrib.admin.ModelAdmin``, it is possible to override |
| 143 |
default filters for all the models fields of the same kind using |
| 144 |
``filter_overrides`` on the ``Meta`` class:: |
| 145 |
|
| 146 |
class ProductFilter(django_filters.FilterSet): |
| 147 |
|
| 148 |
class Meta: |
| 149 |
model = Product |
| 150 |
fields = { |
| 151 |
'name': ['exact'], |
| 152 |
'release_date': ['isnull'], |
| 153 |
} |
| 154 |
filter_overrides = { |
| 155 |
models.CharField: { |
| 156 |
'filter_class': django_filters.CharFilter, |
| 157 |
'extra': lambda f: { |
| 158 |
'lookup_expr': 'icontains', |
| 159 |
}, |
| 160 |
}, |
| 161 |
models.BooleanField: { |
| 162 |
'filter_class': django_filters.BooleanFilter, |
| 163 |
'extra': lambda f: { |
| 164 |
'widget': forms.CheckboxInput, |
| 165 |
}, |
| 166 |
}, |
| 167 |
} |
| 168 |
|
| 169 |
|
| 170 |
Request-based filtering |
| 171 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 172 |
|
| 173 |
The ``FilterSet`` may be initialized with an optional ``request`` argument. If |
| 174 |
a request object is passed, then you may access the request during filtering. |
| 175 |
This allows you to filter by properties on the request, such as the currently |
| 176 |
logged-in user or the ``Accepts-Languages`` header. |
| 177 |
|
| 178 |
.. note:: |
| 179 |
|
| 180 |
It is not guaranteed that a `request` will be provided to the `FilterSet` |
| 181 |
instance. Any code depending on a request should handle the `None` case. |
| 182 |
|
| 183 |
|
| 184 |
Filtering the primary ``.qs`` |
| 185 |
""""""""""""""""""""""""""""" |
| 186 |
|
| 187 |
To filter the primary queryset by the ``request`` object, simply override the |
| 188 |
``FilterSet.qs`` property. For example, you could filter blog articles to only |
| 189 |
those that are published and those that are owned by the logged-in user |
| 190 |
(presumably the author's draft articles). |
| 191 |
|
| 192 |
.. code-block:: python |
| 193 |
|
| 194 |
class ArticleFilter(django_filters.FilterSet): |
| 195 |
|
| 196 |
class Meta: |
| 197 |
model = Article |
| 198 |
fields = [...] |
| 199 |
|
| 200 |
@property |
| 201 |
def qs(self): |
| 202 |
parent = super().qs |
| 203 |
author = getattr(self.request, 'user', None) |
| 204 |
|
| 205 |
return parent.filter(is_published=True) \ |
| 206 |
| parent.filter(author=author) |
| 207 |
|
| 208 |
|
| 209 |
Filtering the related queryset for ``ModelChoiceFilter`` |
| 210 |
"""""""""""""""""""""""""""""""""""""""""""""""""""""""" |
| 211 |
|
| 212 |
The ``queryset`` argument for ``ModelChoiceFilter`` and ``ModelMultipleChoiceFilter`` |
| 213 |
supports callable behavior. If a callable is passed, it will be invoked with the |
| 214 |
``request`` as its only argument. This allows you to perform the same kinds of |
| 215 |
request-based filtering without resorting to overriding ``FilterSet.__init__``. |
| 216 |
|
| 217 |
.. code-block:: python |
| 218 |
|
| 219 |
def departments(request): |
| 220 |
if request is None: |
| 221 |
return Department.objects.none() |
| 222 |
|
| 223 |
company = request.user.company |
| 224 |
return company.department_set.all() |
| 225 |
|
| 226 |
class EmployeeFilter(filters.FilterSet): |
| 227 |
department = filters.ModelChoiceFilter(queryset=departments) |
| 228 |
... |
| 229 |
|
| 230 |
|
| 231 |
Customize filtering with ``Filter.method`` |
| 232 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 233 |
|
| 234 |
You can control the behavior of a filter by specifying a ``method`` to perform |
| 235 |
filtering. View more information in the :ref:`method reference <filter-method>`. |
| 236 |
Note that you may access the filterset's properties, such as the ``request``. |
| 237 |
|
| 238 |
.. code-block:: python |
| 239 |
|
| 240 |
class F(django_filters.FilterSet): |
| 241 |
username = CharFilter(method='my_custom_filter') |
| 242 |
|
| 243 |
class Meta: |
| 244 |
model = User |
| 245 |
fields = ['username'] |
| 246 |
|
| 247 |
def my_custom_filter(self, queryset, name, value): |
| 248 |
return queryset.filter(**{ |
| 249 |
name: value, |
| 250 |
}) |
| 251 |
|
| 252 |
|
| 253 |
The view |
| 254 |
-------- |
| 255 |
|
| 256 |
Now we need to write a view:: |
| 257 |
|
| 258 |
def product_list(request): |
| 259 |
f = ProductFilter(request.GET, queryset=Product.objects.all()) |
| 260 |
return render(request, 'my_app/template.html', {'filter': f}) |
| 261 |
|
| 262 |
If a queryset argument isn't provided then all the items in the default manager |
| 263 |
of the model will be used. |
| 264 |
|
| 265 |
If you want to access the filtered objects in your views, for example if you |
| 266 |
want to paginate them, you can do that. They are in f.qs |
| 267 |
|
| 268 |
|
| 269 |
The URL conf |
| 270 |
------------ |
| 271 |
|
| 272 |
We need a URL pattern to call the view:: |
| 273 |
|
| 274 |
path('list/', views.product_list, name="product-list") |
| 275 |
|
| 276 |
|
| 277 |
The template |
| 278 |
------------ |
| 279 |
|
| 280 |
And lastly we need a template:: |
| 281 |
|
| 282 |
{% extends "base.html" %} |
| 283 |
|
| 284 |
{% block content %} |
| 285 |
<form method="get"> |
| 286 |
{{ filter.form.as_p }} |
| 287 |
<input type="submit" /> |
| 288 |
</form> |
| 289 |
{% for obj in filter.qs %} |
| 290 |
{{ obj.name }} - ${{ obj.price }}<br /> |
| 291 |
{% endfor %} |
| 292 |
{% endblock %} |
| 293 |
|
| 294 |
And that's all there is to it! The ``form`` attribute contains a normal |
| 295 |
Django form, and when we iterate over the ``FilterSet.qs`` we get the objects in |
| 296 |
the resulting queryset. |
| 297 |
|
| 298 |
|
| 299 |
Generic view & configuration |
| 300 |
----------------------------- |
| 301 |
|
| 302 |
In addition to the above usage there is also a class-based generic view |
| 303 |
included in django-filter, which lives at ``django_filters.views.FilterView``. |
| 304 |
You must provide either a ``model`` or ``filterset_class`` argument, similar to |
| 305 |
``ListView`` in Django itself:: |
| 306 |
|
| 307 |
# urls.py |
| 308 |
from django.urls import path |
| 309 |
from django_filters.views import FilterView |
| 310 |
from myapp.models import Product |
| 311 |
|
| 312 |
urlpatterns = [ |
| 313 |
path("list/", FilterView.as_view(model=Product), name="product-list"), |
| 314 |
] |
| 315 |
|
| 316 |
If you provide a ``model`` optionally you can set ``filterset_fields`` to specify a list or a tuple of |
| 317 |
the fields that you want to include for the automatic construction of the filterset class. |
| 318 |
|
| 319 |
You must provide a template at ``<app>/<model>_filter.html`` which gets the |
| 320 |
context parameter ``filter``. Additionally, the context will contain |
| 321 |
``object_list`` which holds the filtered queryset. |
| 322 |
|
| 323 |
A legacy functional generic view is still included in django-filter, although |
| 324 |
its use is deprecated. It can be found at |
| 325 |
``django_filters.views.object_filter``. You must provide the same arguments |
| 326 |
to it as the class based view:: |
| 327 |
|
| 328 |
# urls.py |
| 329 |
from django.urls import path |
| 330 |
from django_filters.views import object_filter |
| 331 |
from myapp.models import Product |
| 332 |
|
| 333 |
urlpatterns = [ |
| 334 |
path("list/", object_filter, {'model': Product}, name="product-list"), |
| 335 |
] |
| 336 |
|
| 337 |
The needed template and its context variables will also be the same as the |
| 338 |
class-based view above. |