Performance: ViewSets and routers
This affects server response time and client load speed by simplifying URL routing and reducing redundant code.
Jump into concepts and practice - no test required
from rest_framework.routers import DefaultRouter from .views import BookViewSet router = DefaultRouter() router.register(r'books', BookViewSet) urlpatterns = router.urls
from django.urls import path from .views import BookList, BookDetail urlpatterns = [ path('books/', BookList.as_view()), path('books/<int:pk>/', BookDetail.as_view()), ]
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual URL patterns with separate views | N/A (server-side) | N/A | N/A | [X] Bad |
| ViewSets with routers | N/A (server-side) | N/A | N/A | [OK] Good |
ViewSets in Django REST Framework?register().add(), include(), and attach() do not exist on routers for this purpose.from rest_framework import routers
router = routers.DefaultRouter()
router.register('books', BookViewSet)from rest_framework import routers
router = routers.DefaultRouter()
router.register('authors', authorsViewSet)ProductViewSet and CategoryViewSet. You also want to customize the basename for CategoryViewSet because it has no queryset attribute. Which code snippet correctly does this?