Skip to content

Intro

Viewsets are a powerful feature provided by Django REST Framework (DRF), not Django itself. They are part of DRF, a toolkit for building Web APIs in Django.

What are Viewsets?

A Viewset is a type of class that allows you to define a set of related views in a single class. Instead of creating separate classes for each HTTP method (e.g., ListAPIView, RetrieveAPIView, CreateAPIView, etc.), you can combine them into one ViewSet class.

Why Use Viewsets?
  • Code Organization: Viewsets help keep your code clean and organized by grouping related actions together.

  • Reduced Redundancy: You don't need to write repetitive code for each action (list, retrieve, create, update, delete).

  • Router Integration: Viewsets work seamlessly with DRF's routers, which can automatically generate the necessary URL patterns for you.

Example

from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Types of Viewsets

  • ModelViewSet: Provides default implementations for typical actions (list, create, retrieve, update, partial_update, and destroy) for a Django model.
  • ReadOnlyModelViewSet: Similar to ModelViewSet, but only allows read-only operations (list and retrieve).

Integration with Routers

To make use of the viewset, you'll typically register it with a router:

from rest_framework.routers import DefaultRouter
from .views import MyModelViewSet

router = DefaultRouter()
router.register(r'mymodel', MyModelViewSet)

urlpatterns = router.urls

This router will automatically generate the following routes:

GET /mymodel/ (list)
GET /mymodel/<pk>/ (retrieve)
POST /mymodel/ (create)
PUT /mymodel/<pk>/ (update)
PATCH /mymodel/<pk>/ (partial_update)
DELETE /mymodel/<pk>/ (destroy)

Conclusion

  • Viewsets are part of Django REST Framework (DRF), not Django itself.
  • They are used to create a group of related views within a single class.
  • Viewsets are tightly integrated with DRF's routers to automatically generate URL patterns.

So, Viewsets are a DRF class and are specific to DRF, not Django.