DRF Views Hierarchy: APIView, Generics & ModelViewSet

DRF provides a spectrum of view classes designed to balance granular control against rapid productivity. Understanding when to use an APIView versus a GenericAPIView or a ModelViewSet is key to writing clean API code.

The 3 DRF View Layers Compared

View Class When to Use Code Effort & Flexibility
APIView Complex custom non-ORM business endpoints (e.g. payment processing, AI generation triggers, custom analytics). Maximum control. You write manual get() and post() methods.
Generic Views (e.g. ListCreateAPIView) Standard database-backed views where you need custom querysets or granular URL endpoints. High productivity. Handles pagination, serialization, and queries automatically.
ModelViewSet Full CRUD REST resources where standard REST conventions (GET, POST, PUT, DELETE) apply. Ultra-rapid. 6 endpoints generated in 5 lines of code, routed via DefaultRouter.

The Gold Standard: ModelViewSet and DefaultRouter

# blog/views.py
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import BlogPost
from .serializers import BlogPostSerializer

class BlogPostViewSet(viewsets.ModelViewSet):
    """A complete RESTful CRUD endpoint for BlogPost records."""
    queryset = BlogPost.objects.all().order_by('-created_at')
    serializer_class = BlogPostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    # Custom endpoint: POST /api/posts/1/publish/
    @action(detail=True, methods=['post'], permission_classes=[permissions.IsAdminUser])
    def publish(self, request, pk=None):
        post = self.get_object()
        post.is_published = True
        post.save()
        return Response({'status': 'article published'}, status=status.HTTP_200_OK)

Wire the ViewSet into your URL schema with DefaultRouter in two lines:

# blog/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BlogPostViewSet

router = DefaultRouter()
router.register(r'posts', BlogPostViewSet, basename='post')

urlpatterns = [
    path('api/', include(router.urls)),
]

What the Router Generated for You

In just those two lines, the Router created 6 REST endpoints: GET /api/posts/, POST /api/posts/, GET /api/posts/1/, PUT /api/posts/1/, PATCH /api/posts/1/, DELETE /api/posts/1/, and POST /api/posts/1/publish/!

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What are the three main tiers of views in DRF?

The three tiers from low-level to high-level are: 1) `APIView` (explicit HTTP method handling: get, post, put, delete), 2) `GenericAPIView` + Mixins (combines model queries with standard CRUD methods like `ListCreateAPIView`), and 3) `ModelViewSet` (binds an entire set of 6 CRUD actions to a single class, routed automatically via `DefaultRouter`).

Q2. What does ModelViewSet provide out of the box?

`ModelViewSet` provides: `list()` (GET /items/), `create()` (POST /items/), `retrieve()` (GET /items/1/), `update()` (PUT /items/1/), `partial_update()` (PATCH /items/1/), and `destroy()` (DELETE /items/1/).

Q3. What is a DRF Router?

A Router (like `DefaultRouter`) automatically wires standard REST URL patterns to a ViewSet without declaring individual URL routes manually.

Q4. How do you add custom actions to a ModelViewSet?

Use the `@action` decorator from `rest_framework.decorators`. For example: `@action(detail=True, methods=['post']) def publish(self, request, pk=None): ...` creates a `/items/1/publish/` endpoint automatically.

Explore Related Django Tutorials & Next Steps

Broaden your backend architecture, REST API design, and production engineering expertise:

DRF Serializers & ModelSerializers

Serialize and validate request data processed by ViewSets.

DRF Authentication & Permissions

Attach permission_classes = [IsAuthenticated] to ViewSets.

DRF Filtering, Ordering & Pagination

Add search, filter, and pagination backends to ModelViewSets.

Generic Class-Based Views (CBVs)

Compare standard Django CBVs with DRF Generic API views.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!