0
0
DjangoHow-ToBeginner · 4 min read

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 class
  • queryset = MyModel.objects.all() - selects all records from the model
  • serializer_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 queryset or serializer_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

PartDescription
viewsets.ModelViewSetBase class providing default CRUD actions
querysetDefines the data records to work with
serializer_classDefines 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.