Creating view sets and routers

ViewSets allow you to define the interactions of your API and let REST framework build the URLs dynamically with a Router object. By using view sets, you can avoid repeating logic for multiple views. View sets include actions for the typical create, retrieve, update, delete operations, which are list(), create(), retrieve(), update(), partial_update(), and destroy().

Let's create a view set for the Course model. Edit the api/views.py file and add the following code to it:

from rest_framework import viewsetsfrom .serializers import CourseSerializerclass CourseViewSet(viewsets.ReadOnlyModelViewSet):    queryset = Course.objects.all()    serializer_class = CourseSerializer

We subclass ReadOnlyModelViewSet, which provides ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.