<metaname="description"content="Django, API, REST, Generic views, API Reference, Mixins, Concrete View Classes, Customizing the generic views, Third party packages">
<p>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.</p>
<p>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.</p>
<p>The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.</p>
<p>If the generic views don't suit the needs of your API, you can drop down to using the regular <code>APIView</code> class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.</p>
<h2id="examples">Examples</h2>
<p>Typically when using the generic views, you'll override the view, and set several class attributes.</p>
<preclass="prettyprint lang-py"><code>from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import generics
from rest_framework.permissions import IsAdminUser
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
paginate_by = 100
</code></pre>
<p>For more complex cases you might also want to override various methods on the view class. For example.</p>
if self.request.accepted_renderer.format == 'html':
return 20
return 100
</code></pre>
<p>For very simple cases you might want to pass through any class attributes using the <code>.as_view()</code> method. For example, your URLconf might include something the following entry.</p>
<p>This class extends REST framework's <code>APIView</code> class, adding commonly required behavior for standard list and detail views.</p>
<p>Each of the concrete generic views provided is built by combining <code>GenericAPIView</code>, with one or more mixin classes.</p>
<h3id="attributes">Attributes</h3>
<p><strong>Basic settings</strong>:</p>
<p>The following attributes control the basic view behavior.</p>
<ul>
<li><code>queryset</code> - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the <code>get_queryset()</code> method.</li>
<li><code>serializer_class</code> - 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 <code>get_serializer_class()</code> method.</li>
<li><code>lookup_field</code> - The model field that should be used to for performing object lookup of individual model instances. Defaults to <code>'pk'</code>. Note that when using hyperlinked APIs you'll need to ensure that <em>both</em> the API views <em>and</em> the serializer classes set the lookup fields if you need to use a custom value.</li>
<li><code>lookup_url_kwarg</code> - 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 <code>lookup_field</code>.</li>
</ul>
<p><strong>Shortcuts</strong>:</p>
<ul>
<li><code>model</code> - This shortcut may be used instead of setting either (or both) of the <code>queryset</code>/<code>serializer_class</code> attributes, although using the explicit style is generally preferred. If used instead of <code>serializer_class</code>, then then <code>DEFAULT_MODEL_SERIALIZER_CLASS</code> setting will determine the base serializer class. Note that <code>model</code> is only ever used for generating a default queryset or serializer class - the <code>queryset</code> and <code>serializer_class</code> attributes are always preferred if provided.</li>
</ul>
<p><strong>Pagination</strong>:</p>
<p>The following attributes are used to control pagination when used with list views.</p>
<ul>
<li><code>paginate_by</code> - The size of pages to use with paginated data. If set to <code>None</code> then pagination is turned off. If unset this uses the same value as the <code>PAGINATE_BY</code> setting, which defaults to <code>None</code>.</li>
<li><code>paginate_by_param</code> - 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 <code>PAGINATE_BY_PARAM</code> setting, which defaults to <code>None</code>.</li>
<li><code>pagination_serializer_class</code> - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> setting.</li>
<li><code>page_kwarg</code> - 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 <code>'page'</code>.</li>
</ul>
<p><strong>Filtering</strong>:</p>
<ul>
<li><code>filter_backends</code> - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the <code>DEFAULT_FILTER_BACKENDS</code> setting.</li>
<p>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 <code>queryset</code> attribute, or the default queryset for the model if the <code>model</code> shortcut is being used.</p>
<p>May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request.</p>
<p>Returns an object instance that should be used for detail views. Defaults to using the <code>lookup_field</code> parameter to filter the base queryset.</p>
<p>May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg.</p>
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>`self.check_object_permissions, and simply return the object from the</code>get_object_or_404` lookup.</p>
<p>Returns the classes that should be used to filter the queryset. Defaults to returning the <code>filter_backends</code> attribute.</p>
<p>May be override to provide more complex behavior with filters, as using different (or even exlusive) lists of filter_backends depending on different criteria.</p>
<p>Returns the class that should be used for the serializer. Defaults to returning the <code>serializer_class</code> attribute, or dynamically generating a serializer class if the <code>model</code> shortcut is being used.</p>
<p>May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of users.</p>
<p>Returns the page size to use with pagination. By default this uses the <code>paginate_by</code> attribute, and may be overridden by the client if the <code>paginate_by_param</code> attribute is set.</p>
<p>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.</p>
<p>The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by <code>GenericAPIView</code>, but they are overridden and used by some of the mixin classes.</p>
<ul>
<li><code>pre_save(self, obj)</code> - A hook that is called before saving an object.</li>
<li><code>post_save(self, obj, created=False)</code> - A hook that is called after saving an object.</li>
<p>The <code>pre_save</code> 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.</p>
Set the object's owner, based on the incoming request.
"""
obj.owner = self.request.user
</code></pre>
<p>Remember that the <code>pre_save()</code> method is not called by <code>GenericAPIView</code> itself, but it is called by <code>create()</code> and <code>update()</code> methods on the <code>CreateModelMixin</code> and <code>UpdateModelMixin</code> classes.</p>
<p><strong>Other methods</strong>:</p>
<p>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 <code>GenericAPIView</code>.</p>
<ul>
<li><code>get_serializer_context(self)</code> - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including <code>'request'</code>, <code>'view'</code> and <code>'format'</code> keys.</li>
<li><code>get_pagination_serializer(self, page)</code> - Returns a serializer instance to use with paginated data.</li>
<li><code>paginate_queryset(self, queryset)</code> - Paginate a queryset if required, either returning a page object, or <code>None</code> if pagination is not configured for this view.</li>
<li><code>filter_queryset(self, queryset)</code> - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.</li>
</ul>
<hr/>
<h1id="mixins">Mixins</h1>
<p>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 <code>.get()</code> and <code>.post()</code> directly. This allows for more flexible composition of behavior.</p>
<h2id="listmodelmixin">ListModelMixin</h2>
<p>Provides a <code>.list(request, *args, **kwargs)</code> method, that implements listing a queryset.</p>
<p>If the queryset is populated, this returns a <code>200 OK</code> response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.</p>
<p>If the queryset is empty this returns a <code>200 OK</code> response, unless the <code>.allow_empty</code> attribute on the view is set to <code>False</code>, in which case it will return a <code>404 Not Found</code>.</p>
<h2id="createmodelmixin">CreateModelMixin</h2>
<p>Provides a <code>.create(request, *args, **kwargs)</code> method, that implements creating and saving a new model instance.</p>
<p>If an object is created this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response. If the representation contains a key named <code>url</code>, then the <code>Location</code> header of the response will be populated with that value.</p>
<p>If the request data provided for creating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<p>Provides a <code>.retrieve(request, *args, **kwargs)</code> method, that implements returning an existing model instance in a response.</p>
<p>If an object can be retrieved this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response. Otherwise it will return a <code>404 Not Found</code>.</p>
<h2id="updatemodelmixin">UpdateModelMixin</h2>
<p>Provides a <code>.update(request, *args, **kwargs)</code> method, that implements updating and saving an existing model instance.</p>
<p>Also provides a <code>.partial_update(request, *args, **kwargs)</code> method, which is similar to the <code>update</code> method, except that all fields for the update will be optional. This allows support for HTTP <code>PATCH</code> requests.</p>
<p>If an object is updated this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If an object is created, for example when making a <code>DELETE</code> request followed by a <code>PUT</code> request to the same URL, this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.</p>
<p>If the request data provided for updating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
<h2id="destroymodelmixin">DestroyModelMixin</h2>
<p>Provides a <code>.destroy(request, *args, **kwargs)</code> method, that implements deletion of an existing model instance.</p>
<p>If an object is deleted this returns a <code>204 No Content</code> response, otherwise it will return a <code>404 Not Found</code>.</p>
<p>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.</p>
<h2id="createapiview">CreateAPIView</h2>
<p>Used for <strong>create-only</strong> endpoints.</p>
<p>Provides a <code>post</code> method handler.</p>
<h1id="customizing-the-generic-views">Customizing the generic views</h1>
<p>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.</p>
<p>Using custom mixins is a good option if you have custom behavior that needs to be used</p>
<h2id="creating-custom-base-classes">Creating custom base classes</h2>
<p>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:</p>
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
generics.RetrieveUpdateDestroyAPIView):
pass
</code></pre>
<p>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.</p>
<p>The <ahref="https://github.com/miki725/django-rest-framework-bulk">django-rest-framework-bulk package</a> implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.</p>