🚀 Supercharge Your Django APIs with ViewSets — Write Less, Do More
If you’ve ever built a REST API in Django, you’ve probably written this pattern a dozen times:
🚀 Supercharge Your Django APIs with ViewSets — Write Less, Do More

If you’ve ever built a REST API in Django, you’ve probably written this pattern a dozen times:
class BookListView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetailView(generics.RetrieveAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookCreateView(generics.CreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookUpdateView(generics.UpdateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDeleteView(generics.DestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
You get the idea — five separate classes, all with the same queryset and serializer_class. 😩
Now imagine collapsing all that into one class and still getting all those endpoints for free.
That’s where Django REST Framework’s ViewSets shine.
💡 What is a ViewSet?
A ViewSet is like your API’s Swiss Army Knife — it combines multiple views (list, retrieve, create, update, delete) into a single class.
Instead of manually defining every endpoint, you declare a ViewSet, and routers automatically create URL patterns for you.
🧱 Let’s Build Something Cool — A Mini Library API
Imagine you’re building a Library Management System. You want an API for managing books. Here’s the model:
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_year = models.IntegerField()
def __str__(self):
return self.title
Now, let’s create the serializer:
# serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
⚙️ Using ViewSets
Here’s where the magic happens:
# views.py
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
That’s it.
No get(), no post(), no put(), no delete().
Now, hook it up with a router:
# urls.py
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet, basename='book')
urlpatterns = router.urls
🌐 Automatically Generated Routes
DRF’s router now gives you all these endpoints automatically:
HTTP MethodURLActionDescriptionGET/books/list()Get all booksPOST/books/create()Add a new bookGET/books/{id}/retrieve()Get a single bookPUT/books/{id}/update()Update an existing bookPATCH/books/{id}/partial_update()Partially updateDELETE/books/{id}/destroy()Delete a book
That’s 6 fully functional API endpoints from just 8 lines of code.
💬 Adding Custom Actions
Need a custom route?
You can extend ViewSets easily with the @action decorator.
Let’s say you want an endpoint /books/recent/ to fetch the 5 latest books:
from rest_framework.decorators import action
from rest_framework.response import Response
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
@action(detail=False, methods=['get'])
def recent(self, request):
recent_books = Book.objects.order_by('-id')[:5]
serializer = self.get_serializer(recent_books, many=True)
return Response(serializer.data)
Now /books/recent/ is automatically available.
No manual URL patterns, no extra classes. 🔥
🧠 Why ViewSets Make Sense
- ✅ Less boilerplate: One class replaces five.
- ✅ Consistency: DRF routers ensure standard RESTful routes.
- ✅ Flexibility: You can still override or extend behavior anytime.
- ✅ Scalability: Easy to add new features like filtering, pagination, permissions, etc.
🧭 When Not to Use ViewSets
- If you need non-RESTful routes (e.g.,
/search/or/report/endpoints). - If your endpoint doesn’t map cleanly to CRUD actions.
- If you need fine-grained control over HTTP method handling.
In those cases, use GenericAPIView or APIView instead.
✨ Final Thoughts
ViewSet is one of the most elegant patterns in Django REST Framework.
It embodies the DRY (Don’t Repeat Yourself) principle perfectly.
If you’re tired of writing the same CRUD boilerplate over and over, give ModelViewSet + DefaultRouter a spin.
Your codebase — and your future self — will thank you.
🚀 TL;DR
With ViewSets, you can turn five views and sixty lines of code into one elegant class and a router — without losing any functionality.
메타데이터
- post_id
- fd366aec322a
- slug
- supercharge-your-django-apis-with-viewsets-write-less-do-more-fd366aec322a
- url
- https://medium.com/@priyansu011/supercharge-your-django-apis-with-viewsets-write-less-do-more-fd366aec322a
- canonical_url
- https://medium.com/@priyansu011/supercharge-your-django-apis-with-viewsets-write-less-do-more-fd366aec322a
- author_url
- https://medium.com/@priyansu011
- status
- ok
- fetched_at
- 2026-07-13 08:05:13