← Back to Django, page 4

django-0079 · Medium mid

How do you add custom endpoints with @action and vary serializers, querysets and permissions per action in a DRF ViewSet?

The @action decorator on a ViewSet method adds an extra route such as /students/{id}/promote/ or /students/top/, registered automatically by the router. Inside a ViewSet, self.action names the current action, so you can override get_queryset(), get_serializer_class() and get_permissions() to return different values for list, retrieve, create or custom actions.

Full answer

Beyond CRUD, resources often need verbs: promote a student, export a list, mark as paid.

python
class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()

    def get_serializer_class(self):
        return StudentListSerializer if self.action == "list" else StudentSerializer

    def get_permissions(self):
        if self.action in ("list", "retrieve"):
            return [IsAuthenticated()]
        return [IsAdminUser()]

    @action(detail=True, methods=["post"], url_path="promote")
    def promote(self, request, pk=None):
        student = self.get_object()
        ...
        return Response({"grade": student.grade})

    @action(detail=False, methods=["get"])
    def top(self, request):
        ...

Details:

  • detail=True makes a route on one object (/students/3/promote/) and get_object() applies queryset filtering, object permissions and 404 handling. detail=False makes a collection route (/students/top/).
  • url_path sets the URL segment; url_name sets the reverse name (student-promote).
  • Per-action overrides: @action(..., permission_classes=[IsAdminUser], serializer_class=PromoteSerializer) passes settings that apply only to that action.
  • get_serializer_class() is the standard hook for a light serializer in list views and a full one for detail views, which also reduces payload and queries.
  • get_queryset() can use self.action to add select_related for detail and only() for list.
  • Use POST (or PATCH) for state changes, not GET, so crawlers and prefetchers cannot trigger them.
  • Make actions idempotent where possible, and wrap multi-step changes in transaction.atomic().
  • Router registration (DefaultRouter().register("students", StudentViewSet)) picks up actions automatically.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "rest_framework.authtoken", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth import get_user_model
from django.db import models, connection
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.test import APIClient


class Student(models.Model):
    name = models.CharField(max_length=40)
    grade = models.IntegerField(default=1)

    class Meta:
        app_label = "school"


User = get_user_model()
with connection.schema_editor() as editor:
    for m in (Student, User):
        editor.create_model(m)


class StudentBrief(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name"]


class StudentFull(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id", "name", "grade"]


class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.order_by("id")

    def get_serializer_class(self):
        return StudentBrief if self.action == "list" else StudentFull

    def get_permissions(self):
        if self.action in ("list", "retrieve", "top"):
            return [IsAuthenticated()]
        return [IsAdminUser()]

    @action(detail=True, methods=["post"])
    def promote(self, request, pk=None):
        student = self.get_object()
        student.grade += 1
        student.save(update_fields=["grade"])
        return Response({"id": student.id, "grade": student.grade})

    @action(detail=False, methods=["get"])
    def top(self, request):
        best = self.get_queryset().order_by("-grade").first()
        return Response(StudentBrief(best).data)


router = DefaultRouter()
router.register("students", StudentViewSet)
urlpatterns = [path("api/", include(router.urls))]

Student.objects.create(name="Asha", grade=3)
Student.objects.create(name="Ravi")
staff = User.objects.create_user("teacher", password="x", is_staff=True)
pupil = User.objects.create_user("pupil", password="x")

c = APIClient()
print(c.get("/api/students/").status_code)
c.force_authenticate(pupil)
print(c.get("/api/students/").json())
print(c.get("/api/students/1/").json())
print(c.post("/api/students/1/promote/").status_code)
c.force_authenticate(staff)
print(c.post("/api/students/1/promote/").json())
c.force_authenticate(pupil)
print(c.get("/api/students/top/").json())
print(sorted({u.name for u in router.urls if u.name and "student" in u.name}))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 403 [{'id': 1, 'name': 'Asha'}, {'id': 2, 'name': 'Ravi'}] {'id': 1, 'name': 'Asha', 'grade': 3} 403 {'id': 1, 'grade': 4} {'id': 1, 'name': 'Asha'} ['student-detail', 'student-list', 'student-promote', 'student-top']

Key points

  • @action adds routes: detail=True per object, False for the collection
  • self.action lets you vary queryset, serializer and permissions
  • get_object() applies filtering and object permissions
  • Use POST for state-changing actions
  • Per-action permission_classes and serializer_class can be passed to the decorator

Common mistakes

  • Using GET for actions that change state
  • Registering permission rules in the decorator but forgetting default permissions
  • Duplicating whole viewsets instead of using self.action
  • Doing extra queries in list because the list serializer is as heavy as the detail one

Follow-ups

  • How does the router name the action routes for reverse()?
  • How do you add object-level permissions to get_object()?
  • How would you make promote idempotent?

Tips

  • Explain detail=True vs False
  • Use self.action to switch behaviour
  • Pick POST for state changes