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 viewsets
from .serializers import CourseSerializer

class CourseViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Course.objects.all()
serializer_class = CourseSerializer

We subclass ReadOnlyModelViewSet, which provides the read-only actions list() and retrieve() to both list objects or retrieve a single object. Edit the api/urls.py file and create a router for our view set as follows:

from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register('courses', views.CourseViewSet)

urlpatterns = [
# ...
path('', include(router.urls)),
]

We create a DefaultRouter object and register our view set with the courses prefix. The router takes charge of generating URLs automatically for our view set.

Open http://127.0.0.1:8000/api/ in your browser. You will see that the router lists all view sets in its base URL, as shown in the following screenshot:

You can access http://127.0.0.1:8000/api/courses/ to retrieve the list of courses.

You can learn more about view sets at https://www.django-rest-framework.org/api-guide/viewsets/. You can also find more information about routers at https://www.django-rest-framework.org/api-guide/routers/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset