Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 77 ยท REST APIs

DRF ViewSets, Routers and Generic Views

Build REST endpoints with Django REST Framework generic views, ModelViewSet and DefaultRouter, add custom @action routes, search, ordering and pagination, with live runnable examples.

A serializer describes data; a view decides what happens to it. DRF offers several view layers so you can pick how much to write yourself. This lesson climbs the ladder with the real library, from generic views to ModelViewSet plus a router, then adds the features every list endpoint eventually needs: custom actions, search, ordering and pagination.

You should know DRF serializers and generic views in plain Django; DRF's generic views follow the same idea with a queryset and a serializer_class.

The ladder: APIView, generic views, ViewSets

Level You write You get
APIView Every HTTP method handler DRF request/response, auth, error handling
Generic views (ListCreateAPIView, RetrieveUpdateDestroyAPIView, ...) queryset + serializer_class List, create, retrieve, update, delete behavior
ViewSet / ModelViewSet One class with actions (list, create, retrieve, update, partial_update, destroy) All actions in one class, URLs from a router

The two generic views below are enough for a classic "collection and member" API:

Python
# read-only
from rest_framework import generics

class BookList(generics.ListCreateAPIView):
    queryset = Book.objects.select_related("author")
    serializer_class = BookSerializer

class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.select_related("author")
    serializer_class = BookSerializer

urlpatterns = [
    path("books/", BookList.as_view()),
    path("books/<int:pk>/", BookDetail.as_view()),
]

A ViewSet collapses these two classes into one. The difference is that it does not map HTTP methods to handlers itself. You bind actions to methods when you build the view, either by hand or with a router.

Binding actions by hand

as_view() on a ViewSet takes a dictionary from HTTP method to action name. This shows exactly what a router automates.

Python ViewSet actions bound manually

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how each outcome follows REST conventions without you writing a single if request.method: 201 on create, 204 with an empty body on delete, 404 for a missing row, 405 for a method that was not bound, and 400 with a field error message when PUT omits a required field.

Routers write the URL patterns

Typing the binding for every ViewSet gets tedious, so a router inspects the class and registers the routes:

Router Adds
SimpleRouter List and detail routes
DefaultRouter The same, plus an API root page at /, and optional format suffixes (.json)

Routes are named <basename>-list and <basename>-detail. The basename comes from the queryset's model name (Book becomes book), or you pass basename= when the ViewSet has no queryset attribute (for example when you override get_queryset()).

Custom actions with @action

CRUD is not always enough. Use the @action decorator to add extra routes to the same ViewSet. detail=True gives a member route (/books/3/borrow/), detail=False gives a collection route (/books/stats/).

Python DefaultRouter, @action, search, ordering and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The router created five route names: book-list and book-detail, plus book-borrow and book-stats from the two @action methods, and api-root for the browsable root page (each also has a .json format-suffix twin, which is why the raw list repeats names). Because get_queryset() is a method, you can read self.request.user or query parameters there, which is the usual place to scope data to the current user.

Choosing serializers and ViewSet types

A ViewSet can pick its serializer per action by overriding get_serializer_class():

Python
# read-only
class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.select_related("author")

    def get_serializer_class(self):
        if self.action == "list":
            return BookListSerializer      # a lean serializer for tables
        return BookDetailSerializer        # the full one for retrieve/create/update

Not every resource should be writable. The ViewSet family has smaller members:

Class Actions
ReadOnlyModelViewSet list, retrieve
GenericViewSet + mixins (ListModelMixin, CreateModelMixin, ...) Exactly the mixins you add
ModelViewSet All six

For example, class CommentViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet) allows reading and posting comments but never editing or deleting them. Combining mixins is better than overriding a method just to raise 405.

Filtering, ordering and pagination

DRF supplies the parts as backends and pagination classes:

  • SearchFilter handles ?search= against search_fields; OrderingFilter handles ?ordering=-pages against ordering_fields. Always list ordering_fields explicitly, so clients cannot sort by a column you did not intend to expose.
  • For field-by-field filters (?genre=classic&min_pages=300), the add-on package django-filter provides DjangoFilterBackend; the hand-written get_queryset() above is fine for one or two filters.
  • PageNumberPagination (?page=2) is simple; LimitOffsetPagination (?limit=20&offset=40) suits infinite scroll; CursorPagination stays stable when rows are inserted while a client pages through, and is the best choice for very large or fast-changing tables.

Set the defaults in REST_FRAMEWORK as in the example, or override pagination_class, filter_backends and permission_classes on a single ViewSet.

Order matters for pagination: an unordered queryset can return overlapping pages. Give the model a Meta.ordering or set a default ordering on the ViewSet. DRF warns when it paginates an unordered queryset.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a router do with a ViewSet?

    A router inspects the ViewSet and generates the URL patterns, named <basename>-list and <basename>-detail, plus routes for any @action methods.
  2. 2. How do you add a route like /books/3/borrow/ to a ModelViewSet?

    @action(detail=True, methods=[...]) creates a member route named after the method; detail=False creates a collection route.
  3. 3. Why should you set ordering_fields explicitly when using OrderingFilter?

    With explicit ordering_fields, ?ordering= only accepts the listed fields. Otherwise any serializer field may be used for sorting.
  4. 4. Which HTTP status does DRF return for a method that has no action bound to the URL?

    If the ViewSet was not bound to that HTTP method on that route, DRF answers 405 Method Not Allowed.

Summary

  • Generic views need only queryset and serializer_class; a ViewSet combines list and detail actions in one class.
  • as_view({"get": "list"}) binds methods to actions by hand; DefaultRouter does it for you and adds an API root.
  • @action(detail=True|False) adds custom routes; get_queryset() and get_serializer_class() customize behavior per request or per action.
  • Use SearchFilter, OrderingFilter and a pagination class for list endpoints; prefer CursorPagination for large, changing data.
  • Pick ReadOnlyModelViewSet or mixins when a resource should not be fully writable.

Next: DRF Authentication: Session, Token and JWT.