ViewSets are essentially just a type of class based view, that doesn’t provide any method handlers, such as get(), post(), etc… but instead has actions, such as list(), retrieve(), create(), etc…

Actions are only bound to methods at the point of instantiating the views.

user_list = UserViewSet.as_view({‘get’: ‘list’}) user_detail = UserViewSet.as_view({‘get’: ‘retrieve’})

Typically, rather than instantiate views from viewsets directly, you’ll register the viewset with a router and let the URL conf be determined automatically.

router = DefaultRouter() router.register(r’users’, UserViewSet, ‘user’) urlpatterns = router.urls

Module Contents

class ViewSetMixin


This is the magic.

Overrides .as_view() so that it takes an actions keyword that performs the binding of HTTP methods to actions on the Resource.

For example, to create a concrete view binding the ‘GET’ and ‘POST’ methods to the ‘list’ and ‘create’ actions…

view = MyViewSet.as_view({‘get’: ‘list’, ‘post’: ‘create’})

classmethod as_view(cls, actions=None, **initkwargs)

Because of the way class based views create a closure around the instantiated view, we need to totally reimplement .as_view, and slightly modify the view function that is created and returned.

initialize_request(self, request, *args, **kwargs)

Set the .action attribute on the view, depending on the request method.

reverse_action(self, url_name, *args, **kwargs)

Reverse the action for the given url_name.

classmethod get_extra_actions(cls)

Get the methods that are marked as an extra ViewSet @action.


Build a map of {names: urls} for the extra actions.

This method will noop if detail was not provided as a view initkwarg.

class ViewSet

Bases:rest_framework.viewsets.ViewSetMixin, rest_framework.views.APIView

The base ViewSet class does not provide any actions by default.

class GenericViewSet

Bases:rest_framework.viewsets.ViewSetMixin, rest_framework.generics.GenericAPIView

The GenericViewSet class does not provide any actions by default, but does include the base set of generic view behavior, such as the get_object and get_queryset methods.

class ReadOnlyModelViewSet

Bases:rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.ListModelMixin, rest_framework.viewsets.GenericViewSet

A viewset that provides default list() and retrieve() actions.

class ModelViewSet

Bases:rest_framework.mixins.CreateModelMixin, rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.UpdateModelMixin, rest_framework.mixins.DestroyModelMixin, rest_framework.mixins.ListModelMixin, rest_framework.viewsets.GenericViewSet

A viewset that provides default create(), retrieve(), update(), partial_update(), destroy() and list() actions.