Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Views and ViewSets

ViewSets: ModelViewSet and ReadOnlyModelViewSet

Group list, create, retrieve, update and delete into one DRF ViewSet class. Learn ModelViewSet, ReadOnlyModelViewSet, GenericViewSet and how actions map to URLs.

With generic views you still write two classes per resource, one for the list URL and one for the detail URL, with the same queryset and serializer_class repeated. A ViewSet merges them into one class. Instead of methods named after HTTP verbs, it has methods named after actions: list, create, retrieve, update, partial_update and destroy. A router (next chapter) then decides which URL and verb reach which action.

ViewSets do not add new power. They are a different way to organize the same ideas, and for model CRUD they usually mean the least code.

ModelViewSet

Python One class, six actions

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 important new call is as_view({"get": "list", "post": "create"}). A viewset's as_view() needs a mapping from HTTP method to action name. A router normally writes these mappings for you, but writing one by hand shows that nothing magical is happening: the same class backs both the list view (no pk) and the detail view (with pk).

The six actions map to the usual REST verbs:

Action Request Purpose
list GET /tasks/ Collection
create POST /tasks/ New object
retrieve GET /tasks/1/ One object
update PUT /tasks/1/ Replace
partial_update PATCH /tasks/1/ Change some fields
destroy DELETE /tasks/1/ Remove

ReadOnlyModelViewSet

When clients may only read, use ReadOnlyModelViewSet. It offers list and retrieve and nothing else, so mutation verbs return 405 and there is no accidental write path.

Python
class CountryViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Country.objects.all()
    serializer_class = CountrySerializer

Building your own: GenericViewSet and mixins

ModelViewSet is GenericViewSet plus the five model mixins from the previous lesson. GenericViewSet has all the helpers (get_queryset, get_object, get_serializer) but no actions. You compose the ones you want:

Python Compose a viewset from mixins

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 the last lines: mapping a verb to an action the class does not have fails loudly with an AttributeError the first time the view is called, so a typo in a mapping cannot silently do nothing. When a router builds the mappings it only includes actions that exist. This pattern, "create and read but never edit or delete", is common for logs, comments and audit records.

Customizing a viewset

Everything you learned about generic views applies, with the addition that you can vary behavior by action:

Python
class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()

    def get_serializer_class(self):
        if self.action == "list":
            return TaskSummarySerializer      # a lighter payload for lists
        return TaskSerializer

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

    def get_queryset(self):
        qs = Task.objects.filter(owner=self.request.user)
        if self.action == "list":
            qs = qs.select_related("project")  # only the list needs the join
        return qs

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

self.action holds the current action name ("list", "retrieve", ...). For an unmapped method such as OPTIONS it is None.

The next example uses self.action to choose a serializer, which is how many APIs return a short list and a detailed single object.

Python Different serializers per action

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.

ViewSet or generic views?

Situation Choose
Standard CRUD on a model with a router ModelViewSet
Read-only resource ReadOnlyModelViewSet
A partial set of actions GenericViewSet + mixins
Not model-backed; custom actions only ViewSet (bare class, you write each action)
One or two bespoke URLs, hand-written routing generic views or APIView

A bare viewsets.ViewSet has no queryset or get_object(); you write list() and retrieve() yourself. It is the viewset counterpart of APIView.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a ViewSet method name represent?

    ViewSets define actions; a router or an as_view() mapping connects HTTP verbs to them.
  2. 2. How do you create a viewset where clients can create and read but not edit or delete?

    Compose only the actions you want on top of GenericViewSet.
  3. 3. How can a viewset pick a different serializer for list and detail?

    self.action holds the current action name, so get_serializer_class() can branch on it.
  4. 4. What does ReadOnlyModelViewSet provide?

    It supports only list and retrieve, so writes get a 405.

Summary

  • A ViewSet groups related actions (list, create, retrieve, update, partial_update, destroy) in one class.
  • ModelViewSet gives all six; ReadOnlyModelViewSet gives two; GenericViewSet + mixins lets you choose.
  • as_view({"get": "list"}) maps verbs to actions; routers do this automatically.
  • self.action lets you vary serializers, permissions and querysets per action.
  • A bare ViewSet is for non-model resources where you write each action yourself.

Next: Custom Actions on ViewSets