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:
- A
querysetto fetch data from. - A
serializer_classfor validating and structuring data. - Helper methods like
get_object()orget_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 Class | Purpose | HTTP Methods | Included Mixins |
|---|---|---|---|
CreateAPIView | Create-only endpoint | POST | CreateModelMixin |
ListAPIView | Read-only collection | GET | ListModelMixin |
RetrieveAPIView | Read-only single instance | GET | RetrieveModelMixin |
DestroyAPIView | Delete-only single instance | DELETE | DestroyModelMixin |
UpdateAPIView | Update-only single instance | PUT, PATCH | UpdateModelMixin |
ListCreateAPIView | Read-write collection | GET, POST | ListModelMixin, CreateModelMixin |
RetrieveUpdateAPIView | Read-update single instance | GET, PUT, PATCH | RetrieveModelMixin, UpdateModelMixin |
RetrieveDestroyAPIView | Read-delete single instance | GET, DELETE | RetrieveModelMixin, DestroyModelMixin |
RetrieveUpdateDestroyAPIView | Read-write-delete single instance | GET, PUT, PATCH, DELETE | RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin |
Example
Using a concrete generic view drastically reduces the amount of code required compared to a standard APIView:
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 = BlogSerializerThese two small classes provide exactly the same functionality as the massive APIView examples seen previously.
