Debian Codegraph @

docs/api-guide/filtering.md

raw
1 ---
2 source:
3 - filters.py
4 ---
5
6 # Filtering
7
8 > The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
9 >
10 > — [Django documentation][cite]
11
12 The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
13
14 The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method.
15
16 Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
17
18 ## Filtering against the current user
19
20 You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.
21
22 You can do so by filtering based on the value of `request.user`.
23
24 For example:
25
26 from myapp.models import Purchase
27 from myapp.serializers import PurchaseSerializer
28 from rest_framework import generics
29
30 class PurchaseList(generics.ListAPIView):
31 serializer_class = PurchaseSerializer
32
33 def get_queryset(self):
34 """
35 This view should return a list of all the purchases
36 for the currently authenticated user.
37 """
38 user = self.request.user
39 return Purchase.objects.filter(purchaser=user)
40
41
42 ## Filtering against the URL
43
44 Another style of filtering might involve restricting the queryset based on some part of the URL.
45
46 For example if your URL config contained an entry like this:
47
48 re_path('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),
49
50 You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
51
52 class PurchaseList(generics.ListAPIView):
53 serializer_class = PurchaseSerializer
54
55 def get_queryset(self):
56 """
57 This view should return a list of all the purchases for
58 the user as determined by the username portion of the URL.
59 """
60 username = self.kwargs['username']
61 return Purchase.objects.filter(purchaser__username=username)
62
63 ## Filtering against query parameters
64
65 A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
66
67 We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
68
69 class PurchaseList(generics.ListAPIView):
70 serializer_class = PurchaseSerializer
71
72 def get_queryset(self):
73 """
74 Optionally restricts the returned purchases to a given user,
75 by filtering against a `username` query parameter in the URL.
76 """
77 queryset = Purchase.objects.all()
78 username = self.request.query_params.get('username')
79 if username is not None:
80 queryset = queryset.filter(purchaser__username=username)
81 return queryset
82
83 ---
84
85 ## Generic Filtering
86
87 As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.
88
89 Generic filters can also present themselves as HTML controls in the browsable API and admin API.
90
91 ![Filter Example](../img/filter-controls.png)
92
93 ### Setting filter backends
94
95 The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example.
96
97 REST_FRAMEWORK = {
98 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
99 }
100
101 You can also set the filter backends on a per-view, or per-viewset basis,
102 using the `GenericAPIView` class-based views.
103
104 import django_filters.rest_framework
105 from django.contrib.auth.models import User
106 from myapp.serializers import UserSerializer
107 from rest_framework import generics
108
109 class UserListView(generics.ListAPIView):
110 queryset = User.objects.all()
111 serializer_class = UserSerializer
112 filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
113
114 ### Filtering and object lookups
115
116 Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
117
118 For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:
119
120 http://example.com/api/products/4675/?category=clothing&max_price=10.00
121
122 ### Overriding the initial queryset
123
124 Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
125
126 class PurchasedProductsList(generics.ListAPIView):
127 """
128 Return a list of all the products that the authenticated
129 user has ever purchased, with optional filtering.
130 """
131 model = Product
132 serializer_class = ProductSerializer
133 filterset_class = ProductFilter
134
135 def get_queryset(self):
136 user = self.request.user
137 return user.purchase_set.all()
138
139 ---
140
141 ## API Guide
142
143 ### DjangoFilterBackend
144
145 The [`django-filter`][django-filter-docs] library includes a `DjangoFilterBackend` class which
146 supports highly customizable field filtering for REST framework.
147
148 To use `DjangoFilterBackend`, first install `django-filter`.
149
150 pip install django-filter
151
152 Then add `'django_filters'` to Django's `INSTALLED_APPS`:
153
154 INSTALLED_APPS = [
155 ...
156 'django_filters',
157 ...
158 ]
159
160 You should now either add the filter backend to your settings:
161
162 REST_FRAMEWORK = {
163 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
164 }
165
166 Or add the filter backend to an individual View or ViewSet.
167
168 from django_filters.rest_framework import DjangoFilterBackend
169
170 class UserListView(generics.ListAPIView):
171 ...
172 filter_backends = [DjangoFilterBackend]
173
174 If all you need is simple equality-based filtering, you can set a `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
175
176 class ProductList(generics.ListAPIView):
177 queryset = Product.objects.all()
178 serializer_class = ProductSerializer
179 filter_backends = [DjangoFilterBackend]
180 filterset_fields = ['category', 'in_stock']
181
182 This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
183
184 http://example.com/api/products?category=clothing&in_stock=True
185
186 For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view.
187 You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs].
188 It's also recommended that you read the section on [DRF integration][django-filter-drf-docs].
189
190
191 ### SearchFilter
192
193 The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin].
194
195 When in use, the browsable API will include a `SearchFilter` control:
196
197 ![Search Filter](../img/search-filter.png)
198
199 The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`.
200
201 from rest_framework import filters
202
203 class UserListView(generics.ListAPIView):
204 queryset = User.objects.all()
205 serializer_class = UserSerializer
206 filter_backends = [filters.SearchFilter]
207 search_fields = ['username', 'email']
208
209 This will allow the client to filter the items in the list by making queries such as:
210
211 http://example.com/api/users?search=russell
212
213 You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation:
214
215 search_fields = ['username', 'email', 'profile__profession']
216
217 For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation:
218
219 search_fields = ['data__breed', 'data__owner__other_pets__0__name']
220
221 By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term.
222
223
224 The search behavior may be specified by prefixing field names in `search_fields` with one of the following characters (which is equivalent to adding `__<lookup>` to the field):
225
226 | Prefix | Lookup | |
227 | ------ | --------------| ------------------ |
228 | `^` | `istartswith` | Starts-with search.|
229 | `=` | `iexact` | Exact matches. |
230 | `$` | `iregex` | Regex search (see warning below). |
231 | `@` | `search` | Full-text search (Currently only supported Django's [PostgreSQL backend][postgres-search]). |
232 | None | `icontains` | Contains search (Default). |
233
234 For example:
235
236 search_fields = ['=username', '=email']
237
238 By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting in the `REST_FRAMEWORK` configuration.
239
240 !!! warning
241 When passing a regex to the filter via the `$` prefix or performing a `iregex` lookup, beware of maliciously crafted regular expressions that may lead to excessive CPU consumption and denial of service (DoS). Consider avoiding regex search for untrusted clients, and familiarize yourself with risky patterns (e.g., catastrophic backtracking).
242
243 #### Accent-insensitive search
244
245 The `UnaccentedSearchFilter` subclass performs accent-insensitive matching, so that a search for `Jeremy` also matches `Jérémy`. It behaves like `SearchFilter`, except the lookups are wrapped with the `unaccent` transform: the default lookup becomes `unaccent__icontains`, `^` becomes `unaccent__istartswith`, `=` becomes `unaccent__iexact`, and `$` becomes `unaccent__iregex`. The `@` (full-text search) prefix is left unchanged, as the `unaccent` transform cannot be combined with a full-text search lookup.
246
247 from rest_framework import filters
248
249 class MyView(generics.ListAPIView):
250 filter_backends = [filters.UnaccentedSearchFilter]
251 search_fields = ['name']
252
253 This is currently only supported on Django's [PostgreSQL backend][postgres-lookups], and requires the `unaccent` extension to be installed and `django.contrib.postgres` to be present in `INSTALLED_APPS`.
254
255 To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request:
256
257 from rest_framework import filters
258
259 class CustomSearchFilter(filters.SearchFilter):
260 def get_search_fields(self, view, request):
261 if request.query_params.get('title_only'):
262 return ['title']
263 return super().get_search_fields(view, request)
264
265 For more details, see the [Django documentation][search-django-admin].
266
267 ---
268
269 ### OrderingFilter
270
271 The `OrderingFilter` class supports simple query parameter controlled ordering of results.
272
273 ![Ordering Filter](../img/ordering-filter.png)
274
275 By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting in the `REST_FRAMEWORK` configuration.
276
277 For example, to order users by username:
278
279 http://example.com/api/users?ordering=username
280
281 The client may also specify reverse orderings by prefixing the field name with '-', like so:
282
283 http://example.com/api/users?ordering=-username
284
285 Multiple orderings may also be specified:
286
287 http://example.com/api/users?ordering=account,username
288
289 #### Specifying which fields may be ordered against
290
291 It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so:
292
293 class UserListView(generics.ListAPIView):
294 queryset = User.objects.all()
295 serializer_class = UserSerializer
296 filter_backends = [filters.OrderingFilter]
297 ordering_fields = ['username', 'email']
298
299 This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.
300
301 If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute.
302
303 If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`.
304
305 class BookingsListView(generics.ListAPIView):
306 queryset = Booking.objects.all()
307 serializer_class = BookingSerializer
308 filter_backends = [filters.OrderingFilter]
309 ordering_fields = '__all__'
310
311 #### Specifying a default ordering
312
313 If an `ordering` attribute is set on the view, this will be used as the default ordering.
314
315 Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.
316
317 class UserListView(generics.ListAPIView):
318 queryset = User.objects.all()
319 serializer_class = UserSerializer
320 filter_backends = [filters.OrderingFilter]
321 ordering_fields = ['username', 'email']
322 ordering = ['username']
323
324 The `ordering` attribute may be either a string or a list/tuple of strings.
325
326 ---
327
328 ## Custom generic filtering
329
330 You can also provide your own generic filtering backend, or write an installable app for other developers to use.
331
332 To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
333
334 As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.
335
336 ### Example
337
338 For example, you might need to restrict users to only being able to see objects they created.
339
340 class IsOwnerFilterBackend(filters.BaseFilterBackend):
341 """
342 Filter that only allows users to see their own objects.
343 """
344 def filter_queryset(self, request, queryset, view):
345 return queryset.filter(owner=request.user)
346
347 We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.
348
349 ### Customizing the interface
350
351 Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature:
352
353 `to_html(self, request, queryset, view)`
354
355 The method should return a rendered HTML string.
356
357 ## Third party packages
358
359 The following third party packages provide additional filter implementations.
360
361 ### Django REST framework filters package
362
363 The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.
364
365 ### Django REST framework full word search filter
366
367 The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match.
368
369 ### Django URL Filter
370
371 [django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s.
372
373 ### drf-url-filters
374
375 [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. A beautiful python package `Voluptuous` is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements.
376
377 [cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters
378 [django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html
379 [django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html
380 [search-django-admin]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields
381 [django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters
382 [django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter
383 [django-url-filter]: https://github.com/miki725/django-url-filter
384 [drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
385 [HStoreField]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#hstorefield
386 [JSONField]: https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.JSONField
387 [postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
388 [postgres-lookups]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/lookups/#unaccent