Overview
AViewSet is a type of class-based view that does not provide method handlers such as .get() or .post(), but instead provides actions such as .list() and .create().
Method handlers for a ViewSet are bound to actions at the point of finalizing the view using the .as_view() method.
Typically, rather than explicitly registering views in a viewset in the urlconf, you’ll register the viewset with a router class that automatically determines the urlconf for you.
ViewSet
Signature:class ViewSet(ViewSetMixin, APIView)
The base ViewSet class does not provide any actions by default. You must explicitly define the action implementations.
Class Methods
as_view()
Signature:as_view(actions=None, **initkwargs)
Returns a callable view that binds HTTP methods to actions.
Mapping of HTTP methods to action names, e.g.,
{'get': 'list', 'post': 'create'}Keyword arguments to pass to the view instance.
get_extra_actions()
Signature:get_extra_actions()
Returns a list of methods marked as extra viewset actions with the @action decorator.
Returns: list[function]
Instance Methods
reverse_action()
Signature:reverse_action(url_name, *args, **kwargs)
Reverses the URL for the given action.
The name of the action to reverse.
Positional URL arguments.
Named URL arguments.
str - The URL for the action
The
basename is provided by the router during ViewSet registration. If not using a router, you must provide the basename argument to .as_view().get_extra_action_url_map()
Signature:get_extra_action_url_map()
Builds a map of {names: urls} for the extra actions.
Returns: dict[str, str]
This method will return an empty dict if detail was not provided as a view initkwarg.
Instance Attributes
The following attributes are available during dispatch:basename
The base name used for URL name generation. Type:str | None
action
The name of the current action (e.g.,list, create, retrieve).
Type: str
detail
Boolean indicating if the current action is configured for a list or detail view. Type:bool | None
suffix
The display suffix for the viewset type - mirrors thedetail attribute.
Type: str | None
name
The display name for the viewset. This argument is mutually exclusive withsuffix.
Type: str | None
description
The display description for the individual view of a viewset. Type:str | None
GenericViewSet
Signature:class GenericViewSet(ViewSetMixin, GenericAPIView)
The GenericViewSet class does not provide any actions by default, but includes the base set of generic view behavior, such as get_object() and get_queryset() methods.
ModelViewSet
Signature:class ModelViewSet(CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, ListModelMixin, GenericViewSet)
Provides default implementations for .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy() actions.
Provided Actions
- list() - List a queryset
- retrieve() - Retrieve a single instance
- create() - Create a new instance
- update() - Update an instance (PUT)
- partial_update() - Partially update an instance (PATCH)
- destroy() - Delete an instance
Dynamic Querysets
You can provide dynamic behavior by overriding methods:When you remove the
queryset property from your ViewSet, any associated router will be unable to derive the basename automatically, so you must specify the basename kwarg during router registration.ReadOnlyModelViewSet
Signature:class ReadOnlyModelViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet)
Provides default .list() and .retrieve() actions.
Provided Actions
- list() - List a queryset
- retrieve() - Retrieve a single instance
Custom ViewSet Base Classes
You may need to provide customViewSet classes that do not have the full set of ModelViewSet actions, or that customize the behavior in some other way.
Action Decorator
@action()
Signature:@action(detail=None, methods=None, **kwargs)
Decorator to mark a method as a routable action.
Whether this action applies to instance/detail requests (True) or collection/list requests (False).
HTTP methods this action responds to. Defaults to
['get'].URL path for this action. Defaults to the method name.
URL name for reversing. Defaults to the method name with underscores replaced by hyphens.
Permission classes for this action.
Serializer class for this action.
Filter backends for this action.
Multiple HTTP Methods
Themethods argument accepts multiple HTTP methods:
HTTPMethod enum:
Customizing URL and Name
- URL path:
^users/{pk}/change-password/$ - URL name:
'user-change_password'
Routing Additional HTTP Methods
Extra actions can map additional HTTP methods to separate methods:Additional mapped methods do not accept arguments beyond
self, request, and URL kwargs.ViewSetMixin
Signature:class ViewSetMixin
The mixin that provides the magic .as_view() behavior for viewsets.
This mixin overrides .as_view() so that it takes an actions keyword that performs the binding of HTTP methods to actions on the resource.
Methods
as_view()
See ViewSet.as_view() above.initialize_request()
Signature:initialize_request(request, *args, **kwargs)
Sets the .action attribute on the view, depending on the request method.
The Django HTTP request.
Positional arguments.
Keyword arguments.
Request
