Last modified: Mar 10, 2025 By Alexander Williams
Django Rest Framework ViewSets and Routers Guide
Django Rest Framework (DRF) is a powerful toolkit for building Web APIs. It simplifies the process of creating APIs by providing tools like ViewSets and Routers. These tools help you write less code and focus on your application logic.
In this guide, we'll explore how to use ViewSets and Routers in DRF. We'll also provide examples to help you understand their usage better.
Table Of Contents
What Are ViewSets?
ViewSets in DRF are a type of class-based view. They combine the logic for handling different HTTP methods like GET, POST, PUT, and DELETE into a single class. This makes your code more organized and easier to maintain.
For example, instead of writing separate views for listing and creating objects, you can use a ModelViewSet
to handle both actions in one place.
Types of ViewSets
DRF provides several types of ViewSets. The most commonly used ones are:
- ModelViewSet: Provides actions for CRUD operations.
- ReadOnlyModelViewSet: Provides read-only actions.
- GenericViewSet: Allows you to define custom actions.
Using ModelViewSet
Let's look at an example of how to use ModelViewSet
. Suppose you have a model called Book
:
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
In this example, BookViewSet
will handle all CRUD operations for the Book
model. The queryset
specifies the data to be used, and serializer_class
defines how the data should be serialized.
What Are Routers?
Routers in DRF automatically generate URL patterns for your ViewSets. This eliminates the need to manually define URLs for each view. DRF provides a DefaultRouter
that works well with ViewSets.
Using DefaultRouter
Here's how you can use DefaultRouter
with the BookViewSet
:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
This code will automatically generate URLs for the BookViewSet
. For example, /books/
will list all books, and /books/1/
will retrieve a specific book.
Custom Actions in ViewSets
Sometimes, you may need to add custom actions to your ViewSets. DRF allows you to do this using the @action
decorator. Here's an example:
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=True, methods=['get'])
def publish(self, request, pk=None):
book = self.get_object()
book.published = True
book.save()
return Response({'status': 'published'})
In this example, the publish
action will mark a book as published. You can access this action via /books/1/publish/
.
Conclusion
ViewSets and Routers are powerful tools in Django Rest Framework. They help you write clean, maintainable code by reducing boilerplate. With ViewSets, you can handle multiple HTTP methods in a single class. Routers automatically generate URLs, saving you time and effort.
If you're new to DRF, check out our guide on Setting Up Your First API with Django Rest Framework. For more advanced topics, explore our article on Django Rest Framework: Serializers and ModelSerializer.
By mastering ViewSets and Routers, you'll be well on your way to building robust APIs with Django Rest Framework.