How to Create Viewset in DRF in Django: Simple Guide
To create a
ViewSet in Django REST Framework (DRF), define a class that inherits from viewsets.ModelViewSet and specify the queryset and serializer_class. Then, register this viewset with a router in your urls.py to handle HTTP requests automatically.Syntax
A ViewSet class in DRF typically inherits from viewsets.ModelViewSet. You must define two main parts: queryset which tells what data to use, and serializer_class which tells how to convert data to and from JSON.
Example parts:
class MyViewSet(viewsets.ModelViewSet):- creates the viewset classqueryset = MyModel.objects.all()- selects all records from the modelserializer_class = MySerializer- uses the serializer to handle data format
python
from rest_framework import viewsets from .models import MyModel from .serializers import MySerializer class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer
Example
This example shows a complete setup of a viewset for a simple Book model. It includes the model, serializer, viewset, and URL routing using DRF's router. The viewset automatically provides list, create, retrieve, update, and delete actions.
python
from django.db import models from rest_framework import serializers, viewsets, routers from django.urls import path, include # Model class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) # Serializer class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'title', 'author'] # ViewSet class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer # Router router = routers.DefaultRouter() router.register(r'books', BookViewSet) # URLs urlpatterns = [ path('', include(router.urls)), ]
Output
When running the Django server and visiting /books/ endpoint, you will see a JSON list of books and can perform CRUD operations via HTTP methods.
Common Pitfalls
Common mistakes when creating viewsets include:
- Not specifying
querysetorserializer_class, which causes errors. - Forgetting to register the viewset with a router in
urls.py, so no URLs are created. - Using a regular Django view instead of a viewset when you want automatic REST actions.
- Not importing required DRF modules correctly.
python
from rest_framework import viewsets # Wrong: Missing queryset and serializer_class class WrongViewSet(viewsets.ModelViewSet): pass # Right: Define queryset and serializer_class class RightViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer
Quick Reference
| Part | Description |
|---|---|
| viewsets.ModelViewSet | Base class providing default CRUD actions |
| queryset | Defines the data records to work with |
| serializer_class | Defines how to convert model instances to JSON and back |
| router.register() | Connects the viewset to URL paths automatically |
Key Takeaways
Always inherit from viewsets.ModelViewSet to create a full-featured viewset.
Define queryset and serializer_class to specify data and serialization.
Register your viewset with a router in urls.py to generate URLs automatically.
Viewsets simplify building REST APIs by handling common HTTP methods.
Avoid missing queryset or serializer_class to prevent runtime errors.