ViewSets and routers help you write less code to handle common web actions like showing, adding, or changing data.
ViewSets and routers in Django
Start learning this pattern below
Jump into concepts and practice - no test required
from rest_framework import viewsets from rest_framework.routers import DefaultRouter class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer router = DefaultRouter() router.register(r'mymodels', MyModelViewSet) urlpatterns = router.urls
ViewSet: A class that groups common actions like list, create, update, delete.
Router: Automatically creates URL patterns for the ViewSet actions.
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializerrouter = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = router.urlsclass ReadOnlyBookViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializerThis example shows a full setup for a simple API to manage fruits. You can list all fruits, add new ones, update, or delete them using the URLs created automatically.
from django.urls import path, include from rest_framework import viewsets from rest_framework.routers import DefaultRouter from rest_framework.serializers import ModelSerializer from django.db import models # Simple model class Fruit(models.Model): name = models.CharField(max_length=100) # Serializer for Fruit class FruitSerializer(ModelSerializer): class Meta: model = Fruit fields = ['id', 'name'] # ViewSet for Fruit class FruitViewSet(viewsets.ModelViewSet): queryset = Fruit.objects.all() serializer_class = FruitSerializer # Router setup router = DefaultRouter() router.register(r'fruits', FruitViewSet) # URL patterns urlpatterns = [ path('', include(router.urls)), ] # Explanation: # This code creates a Fruit model, serializer, and a ViewSet that handles all actions. # The router automatically creates URLs like /fruits/ and /fruits/{id}/ for listing and detail.
Routers save time by creating URLs for you, so you don't write them manually.
ViewSets group related actions, making your code cleaner and easier to read.
You can customize which actions are allowed by choosing different ViewSet classes.
ViewSets group common web actions like list, create, update, and delete.
Routers automatically create URLs for these actions, saving you from writing URL code.
This combination helps you build clean and simple APIs quickly.
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
