0
0
Djangoframework~10 mins

ViewSets and routers in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the correct class for creating a ViewSet.

Django
from rest_framework import [1]
Drag options to blanks, or click blank then click option'
Aviews
Brouters
Cviewsets
Dserializers
Attempts:
3 left
💡 Hint
Common Mistakes
Importing from 'views' instead of 'viewsets'.
Confusing routers with viewsets.
2fill in blank
medium

Complete the code to define a simple ModelViewSet for a model named Book.

Django
class BookViewSet([1]):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
Drag options to blanks, or click blank then click option'
AViewSet
BModelViewSet
CGenericViewSet
DAPIView
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'ViewSet' which requires manual method definitions.
Using 'APIView' which is more low-level.
3fill in blank
hard

Fix the error in the router registration code to correctly register the BookViewSet.

Django
router = routers.DefaultRouter()
router.[1]('books', BookViewSet)
Drag options to blanks, or click blank then click option'
Aregister_viewset
Badd_route
Cinclude
Dregister
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add_route' which does not exist on DefaultRouter.
Using 'include' which is for URL patterns.
4fill in blank
hard

Fill both blanks to complete the URL patterns using the router.

Django
from django.urls import path, include

urlpatterns = [
    path('[1]', include(router.[2]))
]
Drag options to blanks, or click blank then click option'
Aapi/
Burls
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'include' as a string in the path.
Using 'router' instead of 'router.urls'.
5fill in blank
hard

Fill all three blanks to create a custom action in a ViewSet that responds to GET requests.

Django
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)
Drag options to blanks, or click blank then click option'
Aaction
Bpost
Cget
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'post' instead of 'get' for the method.
Setting detail to True when it should be False.
Forgetting to import 'action'.