Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Views and ViewSets

Generic Views and Mixins

Cut DRF boilerplate with GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView and mixins. Learn queryset, serializer_class, get_queryset and perform_create.

The APIView lesson ended with a complaint: every CRUD view repeats the same steps. DRF's generic views package those steps. You declare what the endpoint works on (a queryset and a serializer_class), and a ready-made class supplies the verbs.

Generic views come in three layers: GenericAPIView (the foundation with the shared helpers), mixins (one action each) and concrete views that combine them. Knowing all three lets you pick exactly as much magic as you want.

Concrete views: the quick way

Python Two classes give you full CRUD

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.

That is all the code for list, create, retrieve, update (PUT and PATCH) and delete, plus validation, 404 handling and OPTIONS metadata. The names tell you which verbs you get:

Class Verbs
ListAPIView GET (list)
CreateAPIView POST
RetrieveAPIView GET (one)
DestroyAPIView DELETE
UpdateAPIView PUT, PATCH
ListCreateAPIView GET (list), POST
RetrieveUpdateAPIView GET, PUT, PATCH
RetrieveDestroyAPIView GET, DELETE
RetrieveUpdateDestroyAPIView GET, PUT, PATCH, DELETE

Pick the smallest class that fits. A read-only catalog uses ListAPIView and RetrieveAPIView, so POST and DELETE do not even exist.

What GenericAPIView provides

Every concrete class derives from GenericAPIView, which adds these attributes and methods to APIView:

Member Purpose
queryset The base set of objects
serializer_class Serializer used for input and output
lookup_field, lookup_url_kwarg Which field finds one object (default pk)
pagination_class, filter_backends List behavior (later chapters)
get_queryset() Returns the queryset; override for per-request filtering
get_object() Finds one object by the URL, applies filters, runs object permissions, raises 404
get_serializer() Builds a serializer with context containing request, format and view
filter_queryset(qs) Runs the filter backends

Use get_queryset() whenever the result depends on the request. Do not put request-based queries into the queryset class attribute: it is evaluated once at import time, and its cached results would be shared by every request.

Python get_queryset, lookup_field and perform_create

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.

Three techniques worth remembering:

  • get_queryset() is a security tool. Bob cannot read Ada's task by guessing its URL: the object is simply absent from his queryset, so he gets 404 and does not even learn that it exists.
  • perform_create(serializer) and perform_update(serializer) are the hooks for "save with extra data". Ada's owner came from request.user; Bob's attempt to send owner was ignored because the field is read-only.
  • lookup_field = "slug" switches the URL parameter; the URL pattern's keyword must match (<slug:slug>), or set lookup_url_kwarg.

Mixins: build your own combination

Each concrete view is just GenericAPIView plus mixins. The mixins are ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin and DestroyModelMixin, each adding one method (list, create, retrieve, update, destroy). You wire them to verbs yourself:

Python
from rest_framework import generics, mixins


class TaskList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

This is exactly what ListCreateAPIView does. Reach for mixins when you want an unusual combination, or when you need to run code around the standard action:

Python Wrapping a mixin 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.

Because TaskDetail never mixed in UpdateModelMixin, PUT answers 405 even though the object exists.

Choosing between the layers

  • Concrete generic views for most model endpoints: least code, easiest to read.
  • Mixins when the verb-to-action mapping is unusual.
  • APIView when the endpoint is not about a model.
  • Viewsets (next lesson) when you want one class for list and detail together and automatic URLs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two attributes does a generic view normally need?

    The queryset says which objects, the serializer_class says how to convert them.
  2. 2. Where should you filter objects by the current user?

    get_queryset() runs per request. A class-level queryset is built once at import time.
  3. 3. Which hook adds server-controlled data when saving a new object?

    perform_create receives the validated serializer, so you can call serializer.save(owner=self.request.user).
  4. 4. A view uses RetrieveModelMixin and DestroyModelMixin only. What does PUT return?

    No update method exists, so DRF answers 405 Method Not Allowed.

Summary

  • Generic views need a queryset and a serializer_class; concrete classes such as ListCreateAPIView supply the verbs.
  • GenericAPIView adds get_queryset, get_object, get_serializer, lookup_field and pagination/filter hooks.
  • Use get_queryset() for request-dependent data and as an access-control boundary.
  • perform_create and perform_update add server-side values when saving.
  • Mixins let you assemble custom combinations of actions.

Next: ViewSets