<p>After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.</p>
<p>Django REST framework allows you to combine the logic for a set of related views in a single class, called a <code>ViewSet</code>. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.</p>
<p>A <code>ViewSet</code> class is simply <strong>a type of class-based View, that does not provide any method handlers</strong> such as <code>.get()</code> or <code>.post()</code>, and instead provides actions such as <code>.list()</code> and <code>.create()</code>.</p>
<p>The method handlers for a <code>ViewSet</code> are only bound to the corresponding actions at the point of finalizing the view, using the <code>.as_view()</code> method.</p>
<p>Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.</p>
<p>There are two main advantages of using a <code>ViewSet</code> class over using a <code>View</code> class.</p>
<ul>
<li>Repeated logic can be combined into a single class. In the above example, we only need to specify the <code>queryset</code> once, and it'll be used across multiple views.</li>
<li>By using routers, we no longer need to deal with wiring up the URL conf ourselves.</li>
</ul>
<p>Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.</p>
<p>The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:</p>
<pre><code>class UserViewSet(viewsets.ViewSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.
If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
<p>During dispatch, the following attributes are available on the <code>ViewSet</code>.</p>
<ul>
<li><code>basename</code> - the base to use for the URL names that are created.</li>
<li><code>action</code> - the name of the current action (e.g., <code>list</code>, <code>create</code>).</li>
<li><code>detail</code> - boolean indicating if the current action is configured for a list or detail view.</li>
<li><code>suffix</code> - the display suffix for the viewset type - mirrors the <code>detail</code> attribute.</li>
<li><code>name</code> - the display name for the viewset. This argument is mutually exclusive to <code>suffix</code>.</li>
<li><code>description</code> - the display description for the individual view of a viewset.</li>
</ul>
<p>You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the <code>list</code> action similar to this:</p>
<pre><code>def get_permissions(self):
"""
Instantiates and returns the list of permissions that this view requires.
"""
if self.action == 'list':
permission_classes = [IsAuthenticated]
else:
permission_classes = [IsAdmin]
return [permission() for permission in permission_classes]
</code></pre>
<h2id="marking-extra-actions-for-routing"><aclass="toclink"href="#marking-extra-actions-for-routing">Marking extra actions for routing</a></h2>
<p>If you have ad-hoc methods that should be routable, you can mark them as such with the <code>@action</code> decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the <code>detail</code> argument to <code>True</code> or <code>False</code>. The router will configure its URL patterns accordingly. e.g., the <code>DefaultRouter</code> will configure detail actions to contain <code>pk</code> in their URL patterns.</p>
<p>A more complete example of extra actions:</p>
<pre><code>from django.contrib.auth.models import User
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
<p>The <code>action</code> decorator will route <code>GET</code> requests by default, but may also accept other HTTP methods by setting the <code>methods</code> argument. For example:</p>
<p>The decorator allows you to override any viewset-level configuration such as <code>permission_classes</code>, <code>serializer_class</code>, <code>filter_backends</code>...:</p>
<p>The two new actions will then be available at the urls <code>^users/{pk}/set_password/$</code> and <code>^users/{pk}/unset_password/$</code>. Use the <code>url_path</code> and <code>url_name</code> parameters to change the URL segment and the reverse URL name of the action.</p>
<p>To view all extra actions, call the <code>.get_extra_actions()</code> method.</p>
<h3id="routing-additional-http-methods-for-extra-actions"><aclass="toclink"href="#routing-additional-http-methods-for-extra-actions">Routing additional HTTP methods for extra actions</a></h3>
<p>Extra actions can map additional HTTP methods to separate <code>ViewSet</code> methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.</p>
<p>If you need to get the URL of an action, use the <code>.reverse_action()</code> method. This is a convenience wrapper for <code>reverse()</code>, automatically passing the view's <code>request</code> object and prepending the <code>url_name</code> with the <code>.basename</code> attribute.</p>
<p>Note that the <code>basename</code> is provided by the router during <code>ViewSet</code> registration. If you are not using a router, then you must provide the <code>basename</code> argument to the <code>.as_view()</code> method.</p>
<p>Using the example from the previous section:</p>
<p>The <code>url_name</code> argument for <code>.reverse_action()</code> should match the same argument to the <code>@action</code> decorator. Additionally, this method can be used to reverse the default actions, such as <code>list</code> and <code>create</code>.</p>
<p>The <code>ViewSet</code> class inherits from <code>APIView</code>. You can use any of the standard attributes such as <code>permission_classes</code>, <code>authentication_classes</code> in order to control the API policy on the viewset.</p>
<p>The <code>ViewSet</code> class does not provide any implementations of actions. In order to use a <code>ViewSet</code> class you'll override the class and define the action implementations explicitly.</p>
<p>The <code>GenericViewSet</code> class inherits from <code>GenericAPIView</code>, and provides the default set of <code>get_object</code>, <code>get_queryset</code> methods and other generic view base behavior, but does not include any actions by default.</p>
<p>In order to use a <code>GenericViewSet</code> class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.</p>
<p>The <code>ModelViewSet</code> class inherits from <code>GenericAPIView</code> and includes implementations for various actions, by mixing in the behavior of the various mixin classes.</p>
<p>The actions provided by the <code>ModelViewSet</code> class are <code>.list()</code>, <code>.retrieve()</code>, <code>.create()</code>, <code>.update()</code>, <code>.partial_update()</code>, and <code>.destroy()</code>.</p>
<p>Because <code>ModelViewSet</code> extends <code>GenericAPIView</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
A simple ViewSet for viewing and editing accounts.
"""
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
</code></pre>
<p>Note that you can use any of the standard attributes or method overrides provided by <code>GenericAPIView</code>. For example, to use a <code>ViewSet</code> that dynamically determines the queryset it should operate on, you might do something like this:</p>
A simple ViewSet for viewing and editing the accounts
associated with the user.
"""
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
def get_queryset(self):
return self.request.user.accounts.all()
</code></pre>
<p>Note however that upon removal of the <code>queryset</code> property from your <code>ViewSet</code>, any associated <ahref="../routers/">router</a> will be unable to derive the basename of your Model automatically, and so you will have to specify the <code>basename</code> kwarg as part of your <ahref="../routers/">router registration</a>.</p>
<p>Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.</p>
<p>The <code>ReadOnlyModelViewSet</code> class also inherits from <code>GenericAPIView</code>. As with <code>ModelViewSet</code> it also includes implementations for various actions, but unlike <code>ModelViewSet</code> only provides the 'read-only' actions, <code>.list()</code> and <code>.retrieve()</code>.</p>
<p>As with <code>ModelViewSet</code>, you'll normally need to provide at least the <code>queryset</code> and <code>serializer_class</code> attributes. For example:</p>
<p>Again, as with <code>ModelViewSet</code>, you can use any of the standard attributes and method overrides available to <code>GenericAPIView</code>.</p>
<h1id="custom-viewset-base-classes"><aclass="toclink"href="#custom-viewset-base-classes">Custom ViewSet base classes</a></h1>
<p>You may need to provide custom <code>ViewSet</code> classes that do not have the full set of <code>ModelViewSet</code> actions, or that customize the behavior in some other way.</p>
<p>To create a base viewset class that provides <code>create</code>, <code>list</code> and <code>retrieve</code> operations, inherit from <code>GenericViewSet</code>, and mixin the required actions:</p>
<pre><code>from rest_framework import mixins
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
"""
A viewset that provides `retrieve`, `create`, and `list` actions.
To use it, override the class and set the `.queryset` and
`.serializer_class` attributes.
"""
pass
</code></pre>
<p>By creating your own base <code>ViewSet</code> classes, you can provide common behavior that can be reused in multiple viewsets across your API.</p>
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
</div><!--/.body content-->
<divid="push"></div>
</div><!--/.wrapper -->
<footerclass="span12">
<p>Documentation built with <ahref="http://www.mkdocs.org/">MkDocs</a>.