Debian Codegraph @

docs/api-guide/generic-views.md

raw
1 ---
2 source:
3 - mixins.py
4 - generics.py
5 ---
6
7 # Generic views
8
9 > Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
10 >
11 > — [Django Documentation][cite]
12
13 One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
14
15 The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
16
17 If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
18
19 ## Examples
20
21 Typically when using the generic views, you'll override the view, and set several class attributes.
22
23 from django.contrib.auth.models import User
24 from myapp.serializers import UserSerializer
25 from rest_framework import generics
26 from rest_framework.permissions import IsAdminUser
27
28 class UserList(generics.ListCreateAPIView):
29 queryset = User.objects.all()
30 serializer_class = UserSerializer
31 permission_classes = [IsAdminUser]
32
33 For more complex cases you might also want to override various methods on the view class. For example.
34
35 class UserList(generics.ListCreateAPIView):
36 queryset = User.objects.all()
37 serializer_class = UserSerializer
38 permission_classes = [IsAdminUser]
39
40 def list(self, request):
41 # Note the use of `get_queryset()` instead of `self.queryset`
42 queryset = self.get_queryset()
43 serializer = UserSerializer(queryset, many=True)
44 return Response(serializer.data)
45
46 For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry:
47
48 path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list')
49
50 ---
51
52 ## API Reference
53
54 ### GenericAPIView
55
56 This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
57
58 Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
59
60 #### Attributes
61
62 **Basic settings**:
63
64 The following attributes control the basic view behavior.
65
66 * `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
67 * `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
68 * `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
69 * `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
70
71 **Pagination**:
72
73 The following attributes are used to control pagination when used with list views.
74
75 * `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. Setting `pagination_class=None` will disable pagination on this view.
76
77 **Filtering**:
78
79 * `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting.
80
81 #### Methods
82
83 **Base methods**:
84
85 ##### `get_queryset(self)`
86
87 Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute.
88
89 This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests.
90
91 May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.
92
93 For example:
94
95 def get_queryset(self):
96 user = self.request.user
97 return user.accounts.all()
98
99 !!! tip
100 If the `serializer_class` used in the generic view spans ORM relations, leading to an N+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about N+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
101
102 #### Avoiding N+1 Queries
103
104 When listing objects (e.g. using `ListAPIView` or `ModelViewSet`), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item.
105
106 To prevent this, optimize the queryset in `get_queryset()` or by setting the `queryset` class attribute using [`select_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related) and [`prefetch_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related), depending on the type of relationship.
107
108 **For ForeignKey and OneToOneField**:
109
110 Use `select_related()` to fetch related objects in the same query:
111
112 def get_queryset(self):
113 return Order.objects.select_related("customer", "billing_address")
114
115 **For reverse and many-to-many relationships**:
116
117 Use `prefetch_related()` to efficiently load collections of related objects:
118
119 def get_queryset(self):
120 return Book.objects.prefetch_related("categories", "reviews__user")
121
122 **Combining both**:
123
124 def get_queryset(self):
125 return (
126 Order.objects
127 .select_related("customer")
128 .prefetch_related("items__product")
129 )
130
131 These optimizations reduce repeated database access and improve list view performance.
132
133 ---
134
135 ##### `get_object(self)`
136
137 Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
138
139 May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
140
141 For example:
142
143 def get_object(self):
144 queryset = self.get_queryset()
145 filter = {}
146 for field in self.multiple_lookup_fields:
147 filter[field] = self.kwargs[field]
148
149 obj = get_object_or_404(queryset, **filter)
150 self.check_object_permissions(self.request, obj)
151 return obj
152
153 Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup.
154
155 ##### `filter_queryset(self, queryset)`
156
157 Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
158
159 For example:
160
161 def filter_queryset(self, queryset):
162 filter_backends = [CategoryFilter]
163
164 if 'geo_route' in self.request.query_params:
165 filter_backends = [GeoRouteFilter, CategoryFilter]
166 elif 'geo_point' in self.request.query_params:
167 filter_backends = [GeoPointFilter, CategoryFilter]
168
169 for backend in list(filter_backends):
170 queryset = backend().filter_queryset(self.request, queryset, view=self)
171
172 return queryset
173
174 ##### `get_serializer_class(self)`
175
176 Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute.
177
178 May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.
179
180 For example:
181
182 def get_serializer_class(self):
183 if self.request.user.is_staff:
184 return FullAccountSerializer
185 return BasicAccountSerializer
186
187 !!! note
188 If your implementation branches on `self.request.method`, note that the browsable API calls this method with the request method overridden while [rendering its forms][browsable-api-form-rendering].
189
190 **Save and deletion hooks**:
191
192 The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
193
194 * `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance.
195 * `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance.
196 * `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance.
197
198 These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
199
200 def perform_create(self, serializer):
201 serializer.save(user=self.request.user)
202
203 These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
204
205 def perform_update(self, serializer):
206 instance = serializer.save()
207 send_email_confirmation(user=self.request.user, modified=instance)
208
209 You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example:
210
211 def perform_create(self, serializer):
212 queryset = SignupRequest.objects.filter(user=self.request.user)
213 if queryset.exists():
214 raise ValidationError('You have already signed up')
215 serializer.save(user=self.request.user)
216
217 **Other methods**:
218
219 You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`.
220
221 * `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys.
222 * `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance.
223 * `get_paginated_response(self, data)` - Returns a paginated style `Response` object.
224 * `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
225 * `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
226
227 ---
228
229 ## Mixins
230
231 The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior.
232
233 The mixin classes can be imported from `rest_framework.mixins`.
234
235 ### ListModelMixin
236
237 Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
238
239 If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
240
241 ### CreateModelMixin
242
243 Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
244
245 If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
246
247 If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
248
249 ### RetrieveModelMixin
250
251 Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
252
253 If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
254
255 ### UpdateModelMixin
256
257 Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
258
259 Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests.
260
261 If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
262
263 If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
264
265 ### DestroyModelMixin
266
267 Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
268
269 If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
270
271 ---
272
273 ## Concrete View Classes
274
275 The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
276
277 The view classes can be imported from `rest_framework.generics`.
278
279 ### CreateAPIView
280
281 Used for **create-only** endpoints.
282
283 Provides a `post` method handler.
284
285 Extends: [GenericAPIView], [CreateModelMixin]
286
287 ### ListAPIView
288
289 Used for **read-only** endpoints to represent a **collection of model instances**.
290
291 Provides a `get` method handler.
292
293 Extends: [GenericAPIView], [ListModelMixin]
294
295 ### RetrieveAPIView
296
297 Used for **read-only** endpoints to represent a **single model instance**.
298
299 Provides a `get` method handler.
300
301 Extends: [GenericAPIView], [RetrieveModelMixin]
302
303 ### DestroyAPIView
304
305 Used for **delete-only** endpoints for a **single model instance**.
306
307 Provides a `delete` method handler.
308
309 Extends: [GenericAPIView], [DestroyModelMixin]
310
311 ### UpdateAPIView
312
313 Used for **update-only** endpoints for a **single model instance**.
314
315 Provides `put` and `patch` method handlers.
316
317 Extends: [GenericAPIView], [UpdateModelMixin]
318
319 ### ListCreateAPIView
320
321 Used for **read-write** endpoints to represent a **collection of model instances**.
322
323 Provides `get` and `post` method handlers.
324
325 Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
326
327 ### RetrieveUpdateAPIView
328
329 Used for **read or update** endpoints to represent a **single model instance**.
330
331 Provides `get`, `put` and `patch` method handlers.
332
333 Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
334
335 ### RetrieveDestroyAPIView
336
337 Used for **read or delete** endpoints to represent a **single model instance**.
338
339 Provides `get` and `delete` method handlers.
340
341 Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
342
343 ### RetrieveUpdateDestroyAPIView
344
345 Used for **read-write-delete** endpoints to represent a **single model instance**.
346
347 Provides `get`, `put`, `patch` and `delete` method handlers.
348
349 Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
350
351 ---
352
353 ## Customizing the generic views
354
355 Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.
356
357 ### Creating custom mixins
358
359 For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:
360
361 class MultipleFieldLookupMixin:
362 """
363 Apply this mixin to any view or viewset to get multiple field filtering
364 based on a `lookup_fields` attribute, instead of the default single field filtering.
365 """
366 def get_object(self):
367 queryset = self.get_queryset() # Get the base queryset
368 queryset = self.filter_queryset(queryset) # Apply any filter backends
369 filter = {}
370 for field in self.lookup_fields:
371 if self.kwargs.get(field): # Ignore empty fields.
372 filter[field] = self.kwargs[field]
373 obj = get_object_or_404(queryset, **filter) # Lookup the object
374 self.check_object_permissions(self.request, obj)
375 return obj
376
377 You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
378
379 class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
380 queryset = User.objects.all()
381 serializer_class = UserSerializer
382 lookup_fields = ['account', 'username']
383
384 Using custom mixins is a good option if you have custom behavior that needs to be used.
385
386 ### Creating custom base classes
387
388 If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
389
390 class BaseRetrieveView(MultipleFieldLookupMixin,
391 generics.RetrieveAPIView):
392 pass
393
394 class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
395 generics.RetrieveUpdateDestroyAPIView):
396 pass
397
398 Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.
399
400 ---
401
402 ## PUT as create
403
404 Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not.
405
406 Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses.
407
408 Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious.
409
410 ---
411
412 ## Third party packages
413
414 The following third party packages provide additional generic view implementations.
415
416 ### Django Rest Multiple Models
417
418 [Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request.
419
420
421 [cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views
422 [browsable-api-form-rendering]: ../topics/browsable-api.md#form-rendering
423 [GenericAPIView]: #genericapiview
424 [ListModelMixin]: #listmodelmixin
425 [CreateModelMixin]: #createmodelmixin
426 [RetrieveModelMixin]: #retrievemodelmixin
427 [UpdateModelMixin]: #updatemodelmixin
428 [DestroyModelMixin]: #destroymodelmixin
429 [django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
430 [django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related