You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api-guide/viewsets.md
+20-2Lines changed: 20 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -70,9 +70,10 @@ There are two main advantages of using a `ViewSet` class over using a `View` cla
70
70
71
71
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.
72
72
73
-
## Marking extra actions for routing
74
73
75
-
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
74
+
## ViewSet actions
75
+
76
+
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below:
76
77
77
78
class UserViewSet(viewsets.ViewSet):
78
79
"""
@@ -101,6 +102,23 @@ The default routers included with REST framework will provide routes for a stand
101
102
def destroy(self, request, pk=None):
102
103
pass
103
104
105
+
During dispatch the name of the current action is available via the `.action` attribute.
106
+
You may inspect `.action` to adjust behaviour based on the current action.
107
+
108
+
For example, you could restrict permissions to everything except the `list` action similar to this:
109
+
110
+
def get_permissions(self):
111
+
"""
112
+
Instantiates and returns the list of permissions that this view requires.
113
+
"""
114
+
if self.action == 'list':
115
+
permission_classes = [IsAuthenticated]
116
+
else:
117
+
permission_classes = [IsAdmin]
118
+
return [permission() for permission in permission_classes]
119
+
120
+
## Marking extra actions for routing
121
+
104
122
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators.
105
123
106
124
The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects.
0 commit comments