<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>—<ahref="http://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
</blockquote>
<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>
<h2id="example">Example</h2>
<p>Let's define a simple viewset that can be used to list or retrieve all the users in the system.</p>
<pre><code>from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from myapps.serializers import UserSerializer
from rest_framework import viewsets
from rest_framework.response import Response
class UserViewSet(viewsets.ViewSet):
"""
A simple ViewSet that for listing or retrieving users.
"""
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
</code></pre>
<p>If we need to, we can bind this viewset into two separate views, like so:</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>
<h2id="marking-extra-actions-for-routing">Marking extra actions for routing</h2>
<p>The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, 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.
"""
def list(self, request):
pass
def create(self, request):
pass
def retrieve(self, request, pk=None):
pass
def update(self, request, pk=None):
pass
def partial_update(self, request, pk=None):
pass
def destroy(self, request, pk=None):
pass
</code></pre>
<p>If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the <code>@detail_route</code> or <code>@list_route</code> decorators.</p>
<p>The <code>@detail_route</code> decorator contains <code>pk</code> in its URL pattern and is intended for methods which require a single instance. The <code>@list_route</code> decorator is intended for methods which operate on a list of objects.</p>
<p>For example:</p>
<pre><code>from django.contrib.auth.models import User
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer
<p>These decorators will route <code>GET</code> requests by default, but may also accept other HTTP methods, by using the <code>methods</code> argument. For example:</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></p>
<hr/>
<h1id="api-reference">API Reference</h1>
<h2id="viewset">ViewSet</h2>
<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>
<h2id="genericviewset">GenericViewSet</h2>
<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>
<h2id="modelviewset">ModelViewSet</h2>
<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>, and <code>.destroy()</code>.</p>
<h4id="example_1">Example</h4>
<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, or the <code>model</code> attribute shortcut. 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>
<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 base_name of your Model automatically, and so you you will have to specify the <code>base_name</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>
<h4id="example_2">Example</h4>
<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">Custom ViewSet base classes</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>
<h2id="example_3">Example</h2>
<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>
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>