Skip to content

Generic Views

When building an API, you'll frequently find yourself writing endpoints for standard CRUD operations (Create, Read, Update, Delete).

In the previous section, we saw how Mixins provide the core logic for these operations, but require you to manually bind HTTP verbs (like get() or post()) to the mixin actions.

Django REST Framework provides Generic Views to eliminate this final piece of boilerplate. A Generic View is simply a pre-packaged class that combines GenericAPIView with specific Mixins, and automatically wires up the HTTP methods for you.

The Foundation: GenericAPIView

All concrete generic views inherit from GenericAPIView (which itself extends APIView). GenericAPIView doesn't handle HTTP methods itself, but it provides the essential setup required by the underlying Mixins:

  1. A queryset to fetch data from.
  2. A serializer_class for validating and structuring data.
  3. Helper methods like get_object() or get_serializer().

When using any generic view, you must provide at least a queryset and a serializer_class.

Concrete Generic Views

Most of the time, you will simply inherit from one of these concrete classes. They combine GenericAPIView with specific Mixins and automatically wire up the HTTP methods.

View ClassPurposeHTTP MethodsIncluded Mixins
CreateAPIViewCreate-only endpointPOSTCreateModelMixin
ListAPIViewRead-only collectionGETListModelMixin
RetrieveAPIViewRead-only single instanceGETRetrieveModelMixin
DestroyAPIViewDelete-only single instanceDELETEDestroyModelMixin
UpdateAPIViewUpdate-only single instancePUT, PATCHUpdateModelMixin
ListCreateAPIViewRead-write collectionGET, POSTListModelMixin, CreateModelMixin
RetrieveUpdateAPIViewRead-update single instanceGET, PUT, PATCHRetrieveModelMixin, UpdateModelMixin
RetrieveDestroyAPIViewRead-delete single instanceGET, DELETERetrieveModelMixin, DestroyModelMixin
RetrieveUpdateDestroyAPIViewRead-write-delete single instanceGET, PUT, PATCH, DELETERetrieveModelMixin, UpdateModelMixin, DestroyModelMixin

Example

Using a concrete generic view drastically reduces the amount of code required compared to a standard APIView:

python
from rest_framework import generics
from .models import Blog
from .serializers import BlogSerializer

class BlogList(generics.ListCreateAPIView):
    """
    Handles GET (list) and POST (create)
    """
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

class BlogDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    Handles GET (retrieve), PUT/PATCH (update), and DELETE (destroy)
    """
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer

These two small classes provide exactly the same functionality as the massive APIView examples seen previously.