You can add extra actions to view sets. Let's change our previous CourseEnrollView view into a custom view set action. Edit the api/views.py file and modify the CourseViewSet class to look as follows:
from rest_framework.decorators import detail_routeclass CourseViewSet(viewsets.ReadOnlyModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer @detail_route(methods=['post'], authentication_classes=[BasicAuthentication], permission_classes=[IsAuthenticated]) def enroll(self, request, *args, **kwargs): course = self.get_object() course.students.add(request.user) return Response({'enrolled': True})
We add a custom enroll() method that represents an additional action for this view ...