django-rest-framework/docs/api-guide/generic-views.md

402 lines
19 KiB
Markdown
Raw Normal View History

source: mixins.py
generics.py
2012-09-12 13:12:13 +04:00
# Generic views
> Djangos 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.
>
> — [Django Documentation][cite]
One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
2012-10-02 14:48:25 +04:00
2012-10-03 00:26:15 +04:00
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
2012-10-02 14:48:25 +04:00
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.
2012-10-03 00:26:15 +04:00
## Examples
Typically when using the generic views, you'll override the view, and set several class attributes.
from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
2014-08-29 13:48:16 +04:00
from rest_framework import generics
from rest_framework.permissions import IsAdminUser
2012-10-03 00:26:15 +04:00
class UserList(generics.ListCreateAPIView):
2013-04-25 01:40:24 +04:00
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
2012-10-03 00:26:15 +04:00
paginate_by = 100
For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):
2013-04-25 01:40:24 +04:00
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
2013-04-25 01:40:24 +04:00
def get_paginate_by(self):
2012-10-03 00:26:15 +04:00
"""
Use smaller pagination for HTML representations.
"""
if self.request.accepted_renderer.format == 'html':
2013-04-25 01:40:24 +04:00
return 20
2012-10-03 00:26:15 +04:00
return 100
def list(self, request):
# Note the use of `get_queryset()` instead of `self.queryset`
queryset = self.get_queryset()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
2014-08-27 04:31:08 +04:00
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:
2012-10-03 00:26:15 +04:00
url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
2012-10-02 14:48:25 +04:00
---
# API Reference
2013-04-25 01:40:24 +04:00
## GenericAPIView
This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views.
Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes.
### Attributes
**Basic settings**:
The following attributes control the basic view behavior.
* `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.
2013-04-25 01:40:24 +04:00
* `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.
2013-10-21 12:47:07 +04:00
* `lookup_field` - The model field that should be used to 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.
* `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`.
2013-04-25 01:40:24 +04:00
**Pagination**:
2013-08-29 18:23:34 +04:00
The following attributes are used to control pagination when used with list views.
2013-04-25 01:40:24 +04:00
* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`.
2013-05-28 18:09:23 +04:00
* `paginate_by_param` - The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`.
2013-04-25 01:40:24 +04:00
* `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting.
* `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`.
**Filtering**:
2013-04-25 01:40:24 +04:00
2013-05-07 16:00:44 +04:00
* `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.
2013-04-25 01:40:24 +04:00
**Deprecated attributes**:
* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes. The explicit style is preferred over the `.model` shortcut, and usage of this attribute is now deprecated.
2013-04-25 01:40:24 +04:00
### Methods
**Base methods**:
#### `get_queryset(self)`
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, or the default queryset for the model if the `model` shortcut is being used.
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.
May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.
2013-04-25 01:40:24 +04:00
For example:
def get_queryset(self):
2013-06-26 14:30:27 +04:00
user = self.request.user
return user.accounts.all()
2013-04-25 01:40:24 +04:00
#### `get_object(self)`
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.
2013-04-25 01:40:24 +04:00
For example:
def get_object(self):
queryset = self.get_queryset()
filter = {}
for field in self.multiple_lookup_fields:
filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter)
self.check_object_permissions(self.request, obj)
return obj
2013-04-25 01:40:24 +04:00
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.
2013-10-24 17:39:02 +04:00
#### `get_filter_backends(self)`
Returns the classes that should be used to filter the queryset. Defaults to returning the `filter_backends` attribute.
May be overridden to provide more complex behavior with filters, such as using different (or even exlusive) lists of filter_backends depending on different criteria.
2013-10-24 17:39:02 +04:00
For example:
def get_filter_backends(self):
if "geo_route" in self.request.QUERY_PARAMS:
return (GeoRouteFilter, CategoryFilter)
elif "geo_point" in self.request.QUERY_PARAMS:
return (GeoPointFilter, CategoryFilter)
return (CategoryFilter,)
2013-04-25 01:40:24 +04:00
#### `get_serializer_class(self)`
Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute, or dynamically generating a serializer class if the `model` shortcut is being used.
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.
2013-04-25 01:40:24 +04:00
For example:
def get_serializer_class(self):
if self.request.user.is_staff:
return FullAccountSerializer
return BasicAccountSerializer
#### `get_paginate_by(self)`
2013-08-29 18:23:34 +04:00
Returns the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the client if the `paginate_by_param` attribute is set.
2013-04-25 01:40:24 +04:00
You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.
2013-04-25 01:40:24 +04:00
For example:
def get_paginate_by(self):
2013-06-06 11:56:39 +04:00
if self.request.accepted_renderer.format == 'html':
2013-04-25 01:40:24 +04:00
return 20
return 100
**Save / deletion hooks**:
2013-04-25 01:40:24 +04:00
The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes.
* `pre_save(self, obj)` - A hook that is called before saving an object.
* `post_save(self, obj, created=False)` - A hook that is called after saving an object.
* `pre_delete(self, obj)` - A hook that is called before deleting an object.
* `post_delete(self, obj)` - A hook that is called after deleting an object.
2013-04-25 01:40:24 +04:00
2013-05-05 19:48:12 +04:00
The `pre_save` method in particular is a useful hook 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.
def pre_save(self, obj):
"""
Set the object's owner, based on the incoming request.
"""
obj.owner = self.request.user
Remember that the `pre_save()` method is not called by `GenericAPIView` itself, but it is called by `create()` and `update()` methods on the `CreateModelMixin` and `UpdateModelMixin` classes.
2013-04-25 01:40:24 +04:00
**Other methods**:
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`.
* `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.
* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=False)` - Returns a serializer instance.
2013-04-25 01:40:24 +04:00
* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data.
2013-04-25 20:39:33 +04:00
* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view.
2013-05-08 12:17:27 +04:00
* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.
2013-04-25 01:40:24 +04:00
---
# Mixins
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.
## ListModelMixin
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
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.
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
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.
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.
## RetrieveModelMixin
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
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`.
## UpdateModelMixin
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
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.
If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
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.
## DestroyModelMixin
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
---
2013-04-25 01:40:24 +04:00
# Concrete View Classes
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.
2012-10-25 16:50:48 +04:00
## CreateAPIView
2012-10-02 14:48:25 +04:00
2012-10-25 16:50:48 +04:00
Used for **create-only** endpoints.
2012-10-02 14:48:25 +04:00
2013-05-02 15:08:05 +04:00
Provides a `post` method handler.
2012-10-02 14:48:25 +04:00
2012-10-25 16:50:48 +04:00
Extends: [GenericAPIView], [CreateModelMixin]
2012-10-25 16:50:48 +04:00
## ListAPIView
2012-10-02 14:48:25 +04:00
2012-10-25 16:50:48 +04:00
Used for **read-only** endpoints to represent a **collection of model instances**.
2012-10-02 14:48:25 +04:00
2012-10-25 16:50:48 +04:00
Provides a `get` method handler.
2012-10-02 14:48:25 +04:00
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [ListModelMixin]
2012-10-02 14:48:25 +04:00
## RetrieveAPIView
Used for **read-only** endpoints to represent a **single model instance**.
2012-10-02 14:48:25 +04:00
Provides a `get` method handler.
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [RetrieveModelMixin]
2012-10-25 16:50:48 +04:00
## DestroyAPIView
Used for **delete-only** endpoints for a **single model instance**.
Provides a `delete` method handler.
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [DestroyModelMixin]
2012-10-25 16:50:48 +04:00
## UpdateAPIView
Used for **update-only** endpoints for a **single model instance**.
2013-01-02 17:46:19 +04:00
Provides `put` and `patch` method handlers.
2012-10-25 16:50:48 +04:00
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [UpdateModelMixin]
2012-10-25 16:50:48 +04:00
## ListCreateAPIView
Used for **read-write** endpoints to represent a **collection of model instances**.
Provides `get` and `post` method handlers.
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin]
2012-12-13 19:57:17 +04:00
## RetrieveUpdateAPIView
Used for **read or update** endpoints to represent a **single model instance**.
2013-01-02 17:46:19 +04:00
Provides `get`, `put` and `patch` method handlers.
2012-12-13 19:57:17 +04:00
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin]
2012-12-13 19:57:17 +04:00
## RetrieveDestroyAPIView
Used for **read or delete** endpoints to represent a **single model instance**.
Provides `get` and `delete` method handlers.
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin]
2012-10-02 14:48:25 +04:00
## RetrieveUpdateDestroyAPIView
2012-10-25 16:50:48 +04:00
Used for **read-write-delete** endpoints to represent a **single model instance**.
2012-10-02 14:48:25 +04:00
2013-01-02 17:46:19 +04:00
Provides `get`, `put`, `patch` and `delete` method handlers.
2012-10-02 14:48:25 +04:00
2013-04-25 01:40:24 +04:00
Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
2012-10-02 14:48:25 +04:00
---
# Customizing the generic views
2013-05-09 16:14:20 +04:00
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.
2012-10-02 14:48:25 +04:00
## Creating custom mixins
2012-10-02 14:48:25 +04:00
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:
2012-10-02 14:48:25 +04:00
class MultipleFieldLookupMixin(object):
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
"""
def get_object(self):
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {}
for field in self.lookup_fields:
filter[field] = self.kwargs[field]
return get_object_or_404(queryset, **filter) # Lookup the object
2012-11-18 21:57:02 +04:00
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.
2012-11-18 21:57:02 +04:00
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ('account', 'username')
2012-11-18 21:57:02 +04:00
2014-11-25 15:04:35 +03:00
Using custom mixins is a good option if you have custom behavior that needs to be used.
## Creating custom base classes
2012-10-02 14:48:25 +04:00
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:
2012-10-02 14:48:25 +04:00
class BaseRetrieveView(MultipleFieldLookupMixin,
generics.RetrieveAPIView):
pass
2013-10-24 17:39:02 +04:00
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
generics.RetrieveUpdateDestroyAPIView):
pass
2012-11-18 21:57:02 +04:00
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.
---
# PUT as create
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.
2014-11-07 10:19:26 +03:00
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.
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.
If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
---
# Third party packages
The following third party packages provide additional generic view implementations.
## Django REST Framework bulk
The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
2012-09-12 13:12:13 +04:00
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
2012-10-25 16:50:48 +04:00
[GenericAPIView]: #genericapiview
[ListModelMixin]: #listmodelmixin
[CreateModelMixin]: #createmodelmixin
[RetrieveModelMixin]: #retrievemodelmixin
[UpdateModelMixin]: #updatemodelmixin
[DestroyModelMixin]: #destroymodelmixin
[django-rest-framework-bulk]: https://github.com/miki725/django-rest-framework-bulk