Creating ViewSets and routers
ViewSets allow you to define the interactions of your API and let DRF build URLs dynamically with a Router
object. By using ViewSets, you can avoid repeating logic for multiple views. ViewSets include actions for the following standard operations:
- Create operation:
create()
- Retrieve operation:
list()
andretrieve()
- Update operation:
update()
andpartial_update()
- Delete operation:
destroy()
Let’s create a ViewSet for the Course
model. Edit the api/views.py
file and add the following code highlighted in bold:
from django.db.models import Count
from rest_framework import generics
from rest_framework import viewsets
from courses.api.pagination import StandardPagination
from courses.api.serializers import CourseSerializer, SubjectSerializer
from courses.models import Course, Subject
class CourseViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Course.objects.prefetch_related('modules')
serializer_class...