Debian Codegraph @

docs/guide/rest_framework.txt

raw
1 .. _drf integration:
2
3 ====================
4 Integration with DRF
5 ====================
6
7 Integration with `Django Rest Framework`__ is provided through a DRF-specific ``FilterSet`` and a `filter backend`__. These may be found in the ``rest_framework`` sub-package.
8
9 __ http://www.django-rest-framework.org/
10 __ http://www.django-rest-framework.org/api-guide/filtering/
11
12 Quickstart
13 ----------
14
15 Using the new ``FilterSet`` simply requires changing the import path. Instead of importing from ``django_filters``, import from the ``rest_framework`` sub-package.
16
17 .. code-block:: python
18
19 from django_filters import rest_framework as filters
20
21 class ProductFilter(filters.FilterSet):
22 ...
23
24 Your view class will also need to add ``DjangoFilterBackend`` to the ``filter_backends``.
25
26 .. code-block:: python
27
28 from django_filters import rest_framework as filters
29
30 class ProductList(generics.ListAPIView):
31 queryset = Product.objects.all()
32 serializer_class = ProductSerializer
33 filter_backends = (filters.DjangoFilterBackend,)
34 filterset_fields = ('category', 'in_stock')
35
36 If you want to use the django-filter backend by default, add it to the ``DEFAULT_FILTER_BACKENDS`` setting.
37
38 .. code-block:: python
39
40 # settings.py
41 INSTALLED_APPS = [
42 # ...
43 'rest_framework',
44 'django_filters',
45 ]
46
47 REST_FRAMEWORK = {
48 'DEFAULT_FILTER_BACKENDS': (
49 'django_filters.rest_framework.DjangoFilterBackend',
50 # ...
51 ),
52 }
53
54
55 Adding a FilterSet with ``filterset_class``
56 -------------------------------------------
57
58 To enable filtering with a ``FilterSet``, add it to the ``filterset_class`` parameter on your view class.
59
60 .. code-block:: python
61
62 from rest_framework import generics
63 from django_filters import rest_framework as filters
64 from myapp import Product
65
66
67 class ProductFilter(filters.FilterSet):
68 min_price = filters.NumberFilter(field_name="price", lookup_expr='gte')
69 max_price = filters.NumberFilter(field_name="price", lookup_expr='lte')
70
71 class Meta:
72 model = Product
73 fields = ['category', 'in_stock']
74
75
76 class ProductList(generics.ListAPIView):
77 queryset = Product.objects.all()
78 serializer_class = ProductSerializer
79 filter_backends = (filters.DjangoFilterBackend,)
80 filterset_class = ProductFilter
81
82
83 Using the ``filterset_fields`` shortcut
84 ---------------------------------------
85
86 You may bypass creating a ``FilterSet`` by instead adding ``filterset_fields`` to your view class. This is equivalent to creating a ``FilterSet`` with just :ref:`Meta.fields <fields>`.
87
88
89 .. code-block:: python
90
91 from rest_framework import generics
92 from django_filters import rest_framework as filters
93 from myapp import Product
94
95
96 class ProductList(generics.ListAPIView):
97 queryset = Product.objects.all()
98 filter_backends = (filters.DjangoFilterBackend,)
99 filterset_fields = ('category', 'in_stock')
100
101
102 # Equivalent FilterSet:
103 class ProductFilter(filters.FilterSet):
104 class Meta:
105 model = Product
106 fields = ('category', 'in_stock')
107
108
109 Note that using ``filterset_fields`` and ``filterset_class`` together is not
110 supported.
111
112
113 Overriding FilterSet creation
114 -----------------------------
115
116 ``FilterSet`` creation can be customized by overriding the following methods on the backend class:
117
118 * ``.get_filterset(self, request, queryset, view)``
119 * ``.get_filterset_class(self, view, queryset=None)``
120 * ``.get_filterset_kwargs(self, request, queryset, view)``
121
122 You can override these methods on a case-by-case basis for each view, creating unique backends, or these methods can be used to write your own hooks to the view class.
123
124 .. code-block:: python
125
126 class MyFilterBackend(filters.DjangoFilterBackend):
127 def get_filterset_kwargs(self, request, queryset, view):
128 kwargs = super().get_filterset_kwargs(request, queryset, view)
129
130 # merge filterset kwargs provided by view class
131 if hasattr(view, 'get_filterset_kwargs'):
132 kwargs.update(view.get_filterset_kwargs())
133
134 return kwargs
135
136
137 class BookFilter(filters.FilterSet):
138 def __init__(self, *args, author=None, **kwargs):
139 super().__init__(*args, **kwargs)
140 # do something w/ author
141
142
143 class BookViewSet(viewsets.ModelViewSet):
144 filter_backends = [MyFilterBackend]
145 filterset_class = BookFilter
146
147 def get_filterset_kwargs(self):
148 return {
149 'author': self.get_author(),
150 }
151
152
153 Crispy Forms
154 ------------
155
156 If you are using DRF's browsable API or admin API you may also want to install ``django-crispy-forms``, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML. Note that this isn't actively supported, although pull requests for bug fixes are welcome.
157
158 .. code-block:: bash
159
160 pip install django-crispy-forms
161
162 With crispy forms installed and added to Django's ``INSTALLED_APPS``, the browsable API will present a filtering control for ``DjangoFilterBackend``, like so:
163
164 .. image:: ../assets/form.png
165
166
167 Additional ``FilterSet`` Features
168 ---------------------------------
169
170 The following features are specific to the rest framework FilterSet:
171
172 - ``BooleanFilter``'s use the API-friendly ``BooleanWidget``, which accepts lowercase ``true``/``false``.
173 - Filter generation uses ``IsoDateTimeFilter`` for datetime model fields.
174 - Raised ``ValidationError``'s are reraised as their DRF equivalent.