Complete the code to import the correct class for creating a ViewSet.
from rest_framework import [1]
The viewsets module contains the base classes for creating ViewSets in Django REST Framework.
Complete the code to define a simple ModelViewSet for a model named Book.
class BookViewSet([1]): queryset = Book.objects.all() serializer_class = BookSerializer
ModelViewSet provides default implementations for CRUD operations on models.
Fix the error in the router registration code to correctly register the BookViewSet.
router = routers.DefaultRouter() router.[1]('books', BookViewSet)
The register method is used to add a ViewSet to the router with a URL prefix.
Fill both blanks to complete the URL patterns using the router.
from django.urls import path, include urlpatterns = [ path('[1]', include(router.[2])) ]
The router's urls property provides the URL patterns to include. The path prefix is usually 'api/'.
Fill all three blanks to create a custom action in a ViewSet that responds to GET requests.
from rest_framework.decorators import [1] from rest_framework.response import Response class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer @[1](methods=['[2]'], detail=[3]) def recent(self, request): recent_books = Book.objects.order_by('-published_date')[:5] serializer = self.get_serializer(recent_books, many=True) return Response(serializer.data)
The @action decorator creates a custom route. It should respond to GET requests and be a list route (False).