| 1 |
--- |
| 2 |
source: |
| 3 |
- viewsets.py |
| 4 |
--- |
| 5 |
|
| 6 |
# ViewSets |
| 7 |
|
| 8 |
> 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. |
| 9 |
> |
| 10 |
> — [Ruby on Rails Documentation][cite] |
| 11 |
|
| 12 |
|
| 13 |
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. |
| 14 |
|
| 15 |
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. |
| 16 |
|
| 17 |
The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. |
| 18 |
|
| 19 |
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. |
| 20 |
|
| 21 |
## Example |
| 22 |
|
| 23 |
Let's define a simple viewset that can be used to list or retrieve all the users in the system. |
| 24 |
|
| 25 |
from django.contrib.auth.models import User |
| 26 |
from django.shortcuts import get_object_or_404 |
| 27 |
from myapps.serializers import UserSerializer |
| 28 |
from rest_framework import viewsets |
| 29 |
from rest_framework.response import Response |
| 30 |
|
| 31 |
class UserViewSet(viewsets.ViewSet): |
| 32 |
""" |
| 33 |
A simple ViewSet for listing or retrieving users. |
| 34 |
""" |
| 35 |
def list(self, request): |
| 36 |
queryset = User.objects.all() |
| 37 |
serializer = UserSerializer(queryset, many=True) |
| 38 |
return Response(serializer.data) |
| 39 |
|
| 40 |
def retrieve(self, request, pk=None): |
| 41 |
queryset = User.objects.all() |
| 42 |
user = get_object_or_404(queryset, pk=pk) |
| 43 |
serializer = UserSerializer(user) |
| 44 |
return Response(serializer.data) |
| 45 |
|
| 46 |
If we need to, we can bind this viewset into two separate views, like so: |
| 47 |
|
| 48 |
user_list = UserViewSet.as_view({'get': 'list'}) |
| 49 |
user_detail = UserViewSet.as_view({'get': 'retrieve'}) |
| 50 |
|
| 51 |
!!! warning |
| 52 |
Do not use `.as_view()` with `@action` methods. It bypasses router setup and may ignore action settings like `permission_classes`. Use `DefaultRouter` for actions. |
| 53 |
|
| 54 |
|
| 55 |
Typically, we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. |
| 56 |
|
| 57 |
from myapp.views import UserViewSet |
| 58 |
from rest_framework.routers import DefaultRouter |
| 59 |
|
| 60 |
router = DefaultRouter() |
| 61 |
router.register(r'users', UserViewSet, basename='user') |
| 62 |
urlpatterns = router.urls |
| 63 |
|
| 64 |
!!! warning |
| 65 |
When registering viewsets, do not include a trailing slash in the prefix (e.g., use `r'users'`, not `r'users/'`). Unlike standard Django URL patterns, DRF routers append slashes automatically based on your trailing slash configuration. |
| 66 |
|
| 67 |
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: |
| 68 |
|
| 69 |
class UserViewSet(viewsets.ModelViewSet): |
| 70 |
""" |
| 71 |
A viewset for viewing and editing user instances. |
| 72 |
""" |
| 73 |
serializer_class = UserSerializer |
| 74 |
queryset = User.objects.all() |
| 75 |
|
| 76 |
There are two main advantages of using a `ViewSet` class over using a `View` class. |
| 77 |
|
| 78 |
* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. |
| 79 |
* By using routers, we no longer need to deal with wiring up the URL conf ourselves. |
| 80 |
|
| 81 |
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. |
| 82 |
|
| 83 |
|
| 84 |
## ViewSet actions |
| 85 |
|
| 86 |
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below: |
| 87 |
|
| 88 |
class UserViewSet(viewsets.ViewSet): |
| 89 |
""" |
| 90 |
Example empty viewset demonstrating the standard |
| 91 |
actions that will be handled by a router class. |
| 92 |
|
| 93 |
If you're using format suffixes, make sure to also include |
| 94 |
the `format=None` keyword argument for each action. |
| 95 |
""" |
| 96 |
|
| 97 |
def list(self, request): |
| 98 |
pass |
| 99 |
|
| 100 |
def create(self, request): |
| 101 |
pass |
| 102 |
|
| 103 |
def retrieve(self, request, pk=None): |
| 104 |
pass |
| 105 |
|
| 106 |
def update(self, request, pk=None): |
| 107 |
pass |
| 108 |
|
| 109 |
def partial_update(self, request, pk=None): |
| 110 |
pass |
| 111 |
|
| 112 |
def destroy(self, request, pk=None): |
| 113 |
pass |
| 114 |
|
| 115 |
## Introspecting ViewSet actions |
| 116 |
|
| 117 |
During dispatch, the following attributes are available on the `ViewSet`. |
| 118 |
|
| 119 |
* `basename` - the base to use for the URL names that are created. |
| 120 |
* `action` - the name of the current action (e.g., `list`, `create`). |
| 121 |
* `detail` - boolean indicating if the current action is configured for a list or detail view. |
| 122 |
* `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute. |
| 123 |
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`. |
| 124 |
* `description` - the display description for the individual view of a viewset. |
| 125 |
|
| 126 |
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this: |
| 127 |
|
| 128 |
def get_permissions(self): |
| 129 |
""" |
| 130 |
Instantiates and returns the list of permissions that this view requires. |
| 131 |
""" |
| 132 |
if self.action == 'list': |
| 133 |
permission_classes = [IsAuthenticated] |
| 134 |
else: |
| 135 |
permission_classes = [IsAdminUser] |
| 136 |
return [permission() for permission in permission_classes] |
| 137 |
|
| 138 |
!!! note |
| 139 |
The `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error. |
| 140 |
|
| 141 |
## Marking extra actions for routing |
| 142 |
|
| 143 |
If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns. |
| 144 |
|
| 145 |
A more complete example of extra actions: |
| 146 |
|
| 147 |
from django.contrib.auth.models import User |
| 148 |
from rest_framework import status, viewsets |
| 149 |
from rest_framework.decorators import action |
| 150 |
from rest_framework.response import Response |
| 151 |
from myapp.serializers import UserSerializer, PasswordSerializer |
| 152 |
|
| 153 |
class UserViewSet(viewsets.ModelViewSet): |
| 154 |
""" |
| 155 |
A viewset that provides the standard actions |
| 156 |
""" |
| 157 |
queryset = User.objects.all() |
| 158 |
serializer_class = UserSerializer |
| 159 |
|
| 160 |
@action(detail=True, methods=['post']) |
| 161 |
def set_password(self, request, pk=None): |
| 162 |
user = self.get_object() |
| 163 |
serializer = PasswordSerializer(data=request.data) |
| 164 |
if serializer.is_valid(): |
| 165 |
user.set_password(serializer.validated_data['password']) |
| 166 |
user.save() |
| 167 |
return Response({'status': 'password set'}) |
| 168 |
else: |
| 169 |
return Response(serializer.errors, |
| 170 |
status=status.HTTP_400_BAD_REQUEST) |
| 171 |
|
| 172 |
@action(detail=False) |
| 173 |
def recent_users(self, request): |
| 174 |
recent_users = User.objects.all().order_by('-last_login') |
| 175 |
|
| 176 |
page = self.paginate_queryset(recent_users) |
| 177 |
if page is not None: |
| 178 |
serializer = self.get_serializer(page, many=True) |
| 179 |
return self.get_paginated_response(serializer.data) |
| 180 |
|
| 181 |
serializer = self.get_serializer(recent_users, many=True) |
| 182 |
return Response(serializer.data) |
| 183 |
|
| 184 |
|
| 185 |
The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example: |
| 186 |
|
| 187 |
@action(detail=True, methods=['post', 'delete']) |
| 188 |
def unset_password(self, request, pk=None): |
| 189 |
... |
| 190 |
|
| 191 |
Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above: |
| 192 |
|
| 193 |
from http import HTTPMethod |
| 194 |
|
| 195 |
@action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE]) |
| 196 |
def unset_password(self, request, pk=None): |
| 197 |
... |
| 198 |
|
| 199 |
The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...: |
| 200 |
|
| 201 |
@action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) |
| 202 |
def set_password(self, request, pk=None): |
| 203 |
... |
| 204 |
|
| 205 |
The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`. Use the `url_path` and `url_name` parameters to change the URL segment and the reverse URL name of the action. |
| 206 |
|
| 207 |
To view all extra actions, call the `.get_extra_actions()` method. |
| 208 |
|
| 209 |
### Routing additional HTTP methods for extra actions |
| 210 |
|
| 211 |
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. |
| 212 |
|
| 213 |
```python |
| 214 |
@action(detail=True, methods=["put"], name="Change Password") |
| 215 |
def password(self, request, pk=None): |
| 216 |
"""Update the user's password.""" |
| 217 |
... |
| 218 |
|
| 219 |
|
| 220 |
@password.mapping.delete |
| 221 |
def delete_password(self, request, pk=None): |
| 222 |
"""Delete the user's password.""" |
| 223 |
... |
| 224 |
``` |
| 225 |
|
| 226 |
## Reversing action URLs |
| 227 |
|
| 228 |
If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute. |
| 229 |
|
| 230 |
Note that the `basename` is provided by the router during `ViewSet` registration. If you are not using a router, then you must provide the `basename` argument to the `.as_view()` method. |
| 231 |
|
| 232 |
Using the example from the previous section: |
| 233 |
|
| 234 |
```pycon |
| 235 |
>>> view.reverse_action("set-password", args=["1"]) |
| 236 |
'http://localhost:8000/api/users/1/set_password' |
| 237 |
``` |
| 238 |
|
| 239 |
Alternatively, you can use the `url_name` attribute set by the `@action` decorator. |
| 240 |
|
| 241 |
```pycon |
| 242 |
>>> view.reverse_action(view.set_password.url_name, args=["1"]) |
| 243 |
'http://localhost:8000/api/users/1/set_password' |
| 244 |
``` |
| 245 |
|
| 246 |
The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`. |
| 247 |
|
| 248 |
--- |
| 249 |
|
| 250 |
## API Reference |
| 251 |
|
| 252 |
### ViewSet |
| 253 |
|
| 254 |
The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. |
| 255 |
|
| 256 |
The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. |
| 257 |
|
| 258 |
### GenericViewSet |
| 259 |
|
| 260 |
The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default. |
| 261 |
|
| 262 |
In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. |
| 263 |
|
| 264 |
### ModelViewSet |
| 265 |
|
| 266 |
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. |
| 267 |
|
| 268 |
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`. |
| 269 |
|
| 270 |
#### Example |
| 271 |
|
| 272 |
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: |
| 273 |
|
| 274 |
class AccountViewSet(viewsets.ModelViewSet): |
| 275 |
""" |
| 276 |
A simple ViewSet for viewing and editing accounts. |
| 277 |
""" |
| 278 |
queryset = Account.objects.all() |
| 279 |
serializer_class = AccountSerializer |
| 280 |
permission_classes = [IsAccountAdminOrReadOnly] |
| 281 |
|
| 282 |
Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: |
| 283 |
|
| 284 |
class AccountViewSet(viewsets.ModelViewSet): |
| 285 |
""" |
| 286 |
A simple ViewSet for viewing and editing the accounts |
| 287 |
associated with the user. |
| 288 |
""" |
| 289 |
serializer_class = AccountSerializer |
| 290 |
permission_classes = [IsAccountAdminOrReadOnly] |
| 291 |
|
| 292 |
def get_queryset(self): |
| 293 |
return self.request.user.accounts.all() |
| 294 |
|
| 295 |
Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the basename of your Model automatically, and so you will have to specify the `basename` kwarg as part of your [router registration][routers]. |
| 296 |
|
| 297 |
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. |
| 298 |
|
| 299 |
### ReadOnlyModelViewSet |
| 300 |
|
| 301 |
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. |
| 302 |
|
| 303 |
#### Example |
| 304 |
|
| 305 |
As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: |
| 306 |
|
| 307 |
class AccountViewSet(viewsets.ReadOnlyModelViewSet): |
| 308 |
""" |
| 309 |
A simple ViewSet for viewing accounts. |
| 310 |
""" |
| 311 |
queryset = Account.objects.all() |
| 312 |
serializer_class = AccountSerializer |
| 313 |
|
| 314 |
Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. |
| 315 |
|
| 316 |
## Custom ViewSet base classes |
| 317 |
|
| 318 |
You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way. |
| 319 |
|
| 320 |
### Example |
| 321 |
|
| 322 |
To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions: |
| 323 |
|
| 324 |
from rest_framework import mixins, viewsets |
| 325 |
|
| 326 |
class CreateListRetrieveViewSet(mixins.CreateModelMixin, |
| 327 |
mixins.ListModelMixin, |
| 328 |
mixins.RetrieveModelMixin, |
| 329 |
viewsets.GenericViewSet): |
| 330 |
""" |
| 331 |
A viewset that provides `retrieve`, `create`, and `list` actions. |
| 332 |
|
| 333 |
To use it, override the class and set the `.queryset` and |
| 334 |
`.serializer_class` attributes. |
| 335 |
""" |
| 336 |
pass |
| 337 |
|
| 338 |
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. |
| 339 |
|
| 340 |
[cite]: https://guides.rubyonrails.org/action_controller_overview.html |
| 341 |
[routers]: routers.md |