← Back to Django, page 2

django-0029 · Medium mid

What are ViewSets and routers in Django REST Framework, and when would you use APIView or generic views instead?

A ViewSet groups the actions for one resource (list, create, retrieve, update, partial_update, destroy) in one class, and a router generates the URL patterns for them. ModelViewSet gives full CRUD from a queryset and serializer_class. Use @action for extra endpoints, generic views (ListCreateAPIView and friends) for fewer actions, and APIView when the endpoint does not fit the resource pattern.

Full answer

DRF has three layers of view abstraction:

  • APIView: like Django's View, with DRF request parsing, authentication, permissions, throttling and content negotiation. You write get(), post() yourself.
  • Generic views and mixins: ListAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView. You set queryset and serializer_class, and override hooks such as get_queryset() and perform_create().
  • ViewSets: one class with actions instead of HTTP methods. ModelViewSet gives list, create, retrieve, update, partial_update and destroy. ReadOnlyModelViewSet gives only list and retrieve.

A router maps actions to URLs:

python
router = DefaultRouter()
router.register("books", BookViewSet, basename="book")
urlpatterns = router.urls

This produces /books/ (GET list, POST create) and /books/{pk}/ (GET, PUT, PATCH, DELETE), with names like book-list and book-detail. DefaultRouter also adds an API root view.

Extra endpoints use @action:

python
@action(detail=True, methods=["post"])
def issue(self, request, pk=None): ...

which becomes POST /books/{pk}/issue/.

Hooks worth knowing:

  • get_queryset(): scope by user, add select_related.
  • get_serializer_class(): different serializers for list vs detail, or by self.action.
  • perform_create(serializer): serializer.save(owner=self.request.user).
  • get_permissions(): different permissions per action.

Choose ViewSets when a resource really is CRUD. When an endpoint is a command ("recalculate fees for March"), an APIView or a single @action is clearer than forcing it into CRUD.

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
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.db.models import F
from django.urls import include, path
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.routers import DefaultRouter
from rest_framework.test import APIClient


class Book(models.Model):
    title = models.CharField(max_length=60)
    copies = models.PositiveIntegerField(default=1)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Book)


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "copies"]


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.order_by("id")
    serializer_class = BookSerializer
    authentication_classes = []
    permission_classes = []

    @action(detail=True, methods=["post"])
    def issue(self, request, pk=None):
        updated = Book.objects.filter(pk=pk, copies__gt=0).update(copies=F("copies") - 1)
        if not updated:
            return Response({"detail": "No copies left"}, status=409)
        return Response(BookSerializer(Book.objects.get(pk=pk)).data)


router = DefaultRouter()
router.register("books", BookViewSet, basename="book")
urlpatterns = [path("api/", include(router.urls))]
settings.ROOT_URLCONF = __name__

print(sorted({p.name for p in router.urls if p.name}))

c = APIClient()
print(c.post("/api/books/", {"title": "Kanthapura", "copies": 1}, format="json").json())
print(c.get("/api/books/").json())
print(c.post("/api/books/1/issue/").json())
r = c.post("/api/books/1/issue/")
print(r.status_code, r.json())
print(c.patch("/api/books/1/", {"copies": 4}, format="json").json())
print(c.delete("/api/books/1/").status_code)

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` (run here with DRF 3.16+). Authentication and permissions are switched off on this ViewSet only to keep the demo short; see the auth question for real settings. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['api-root', 'book-detail', 'book-issue', 'book-list'] {'id': 1, 'title': 'Kanthapura', 'copies': 1} [{'id': 1, 'title': 'Kanthapura', 'copies': 1}] {'id': 1, 'title': 'Kanthapura', 'copies': 0} 409 {'detail': 'No copies left'} {'id': 1, 'title': 'Kanthapura', 'copies': 4} 204

Key points

  • APIView < generic views < ViewSets in abstraction
  • ModelViewSet gives full CRUD; routers build URLs
  • @action adds custom endpoints
  • Override get_queryset, get_serializer_class, perform_create
  • Use APIView for endpoints that are commands, not resources

Common mistakes

  • Using ModelViewSet for endpoints that should not allow delete or update
  • Forgetting basename when the ViewSet has no queryset attribute
  • Putting user scoping in the serializer instead of get_queryset()
  • Creating a whole ViewSet for a single command-like endpoint

Follow-ups

  • How would you allow only list and create on a resource?
  • How do you use a different serializer for the list action?
  • What URL does @action(detail=False) produce?

Tips

  • Lay out the three abstraction levels
  • Show a custom @action with a real business reason
  • Mention get_queryset scoping for security