Discover how to save hours of repetitive work by letting Django handle your API routes for you!
Why ViewSets and routers in Django? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web API where you have to write separate functions for listing, creating, updating, and deleting items, then manually connect each function to a URL.
This manual approach means writing repetitive code for each action and carefully mapping URLs to functions, which is slow, error-prone, and hard to maintain as your API grows.
ViewSets and routers let you group related actions in one place and automatically create URL routes, so you write less code and avoid mistakes.
def list_items(request): ... def create_item(request): ... urlpatterns = [path('items/', list_items), path('items/create/', create_item)]
from rest_framework.viewsets import ViewSet from rest_framework.routers import DefaultRouter class ItemViewSet(ViewSet): ... router = DefaultRouter() router.register('items', ItemViewSet) urlpatterns = router.urls
This makes building and scaling APIs faster and cleaner by handling routing and actions automatically.
When creating an online store API, you can quickly add product listing, detail, and update features without writing separate URL patterns for each.
Manual URL and action handling is repetitive and error-prone.
ViewSets group related actions in one class.
Routers automatically generate URL patterns from ViewSets.
Practice
ViewSets in Django REST Framework?Solution
Step 1: Understand what ViewSets do
ViewSets group common actions such as list, create, update, and delete into one class to simplify API views.Step 2: Compare with other options
Options B, C, and D describe unrelated tasks: models, templates, and authentication, which are not the main purpose of ViewSets.Final Answer:
To group common web actions like list, create, update, and delete in one class -> Option AQuick Check:
ViewSets group actions = A [OK]
- Confusing ViewSets with models
- Thinking ViewSets handle templates
- Assuming ViewSets manage authentication
Solution
Step 1: Recall the router method to register ViewSets
The correct method to register a ViewSet with a router isregister().Step 2: Verify method names
Methods likeadd(),include(), andattach()do not exist on routers for this purpose.Final Answer:
router.register('items', ItemViewSet) -> Option CQuick Check:
Use register() to add ViewSets to routers [OK]
- Using non-existent router methods like add or include
- Confusing router registration with URL inclusion
- Forgetting to pass the ViewSet class
from rest_framework import routers
router = routers.DefaultRouter()
router.register('books', BookViewSet)Solution
Step 1: Understand DefaultRouter URL patterns
DefaultRouter creates URLs like /books/ for listing and creating, and /books/{pk}/ for retrieve, update, and delete actions.Step 2: Compare with other options
Options A, C, and D use incorrect URL paths that are not generated by DefaultRouter automatically.Final Answer:
/books/ for list and create, /books/{pk}/ for retrieve, update, delete -> Option DQuick Check:
DefaultRouter creates standard REST URLs = B [OK]
- Expecting custom URL suffixes like /list or /create
- Not knowing DefaultRouter auto-generates URLs
- Confusing URL patterns with manual URL configs
from rest_framework import routers
router = routers.DefaultRouter()
router.register('authors', authorsViewSet)Solution
Step 1: Check the ViewSet class name
Python class names should be capitalized. 'authorsViewSet' is likely a typo and should be 'AuthorsViewSet'.Step 2: Validate other options
DefaultRouter is valid here, basename is optional if ViewSet has queryset, and 'authors' is a valid URL prefix.Final Answer:
The ViewSet class name should be capitalized as AuthorsViewSet -> Option AQuick Check:
Class names must be capitalized = A [OK]
- Using lowercase for class names
- Thinking basename is always required
- Confusing router types unnecessarily
ProductViewSet and CategoryViewSet. You also want to customize the basename for CategoryViewSet because it has no queryset attribute. Which code snippet correctly does this?Solution
Step 1: Understand basename usage
If a ViewSet lacks a queryset attribute, you must provide a basename when registering it with the router.Step 2: Check the code snippets
router.register('products', ProductViewSet) router.register('categories', CategoryViewSet, basename='category') correctly registers ProductViewSet without basename (assuming it has queryset) and CategoryViewSet with basename='category'. Other options either omit basename or misuse it.Final Answer:
router.register('products', ProductViewSet) router.register('categories', CategoryViewSet, basename='category') -> Option BQuick Check:
Provide basename if no queryset = C [OK]
- Omitting basename for ViewSets without queryset
- Using wrong basename strings
- Adding basename unnecessarily
