ViewSet & Router (DRF)

A ViewSet groups the logic for a set of related API endpoints (list, retrieve, create, update, destroy) into one class. Paired with a DRF Router, it auto-generates the URL routes for full CRUD on a resource.

Django

A ViewSet bundles the standard REST actions for a resource into a single class rather than separate views per endpoint. ModelViewSet, the most common, provides all of list/create/retrieve/update/partial_update/destroy from just a queryset and serializer_class.

Routers eliminate manual URL wiring: you register a viewset with a DefaultRouter, and it generates the conventional URLs (/posts/ for the collection, /posts/{id}/ for an item) mapped to the right actions. This keeps an API's routing DRY and consistent.

When you need only some actions, ReadOnlyModelViewSet gives just list and retrieve, or you add custom routes with the @action decorator. ViewSets trade a little explicitness for a lot less boilerplate compared to writing each APIView by hand.

Syntax

router.register("posts", PostViewSet)

Examples

Python

from rest_framework.routers import DefaultRouter
from .views import PostViewSet

router = DefaultRouter()
router.register("posts", PostViewSet)

# urls.py
# urlpatterns = router.urls  -> /posts/ and /posts/<pk>/

Learn it in a lesson

See also

Back to the Dictionary