Viewsets in Django REST Framework
In this tutorial, we will explore the concept of viewsets in Django REST Framework. Viewsets in Django REST Framework (DRF) provide a streamlined way to handle CRUD (Create, Read, Update, Delete) operations on our API endpoints.
Viewsets in DRF
-
Viewsets are a powerful and efficient way to define the logic for handling API endpoints that perform CRUD operations on resources.
-
Viewsets abstract away a lot of the boilerplate code commonly associated with creating these operations, making it easier and quicker to build RESTful APIs.
-
Viewsets combine the behavior of multiple DRF views, such as ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, and DestroyAPIView, into a single class.
Implement the Viewset
views.py
from rest_framework import viewsets
from .models import Students
from .serializers import StudentsSerializer
class StudentsViewSet(viewsets.ModelViewSet):
queryset = Students.objects.all()
serializer_class = StudentsSerializer
The above code creates a Viewset named StudentsViewSet that provides default CRUD operations (list, create, retrieve, update, delete) for the Students model.
app/urls.py
from rest_framework import routers
from .views import StudentsViewSet
router = routers.DefaultRouter()
router.register(r'students', StudentsViewSet)
urlpatterns = router.urls
In above code, we have used Django REST Framework's routers module to automatically generate URL routes for the StudentsViewSet. The code registers the StudentsViewSet as a resource named 'students' and generates appropriate URL patterns, which are then assigned to the urlpatterns.
Result