0
0
Djangoframework~30 mins

ViewSets and routers in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple API with Django ViewSets and Routers
📖 Scenario: You are creating a small web API for a bookstore. The API will allow users to see a list of books and details about each book.
🎯 Goal: Build a Django API using ViewSets and routers to manage book data easily.
📋 What You'll Learn
Create a Django model for books with fields: title and author
Create a serializer for the Book model
Create a ViewSet for the Book model
Use a router to automatically generate URL routes for the Book API
💡 Why This Matters
🌍 Real World
APIs built with Django ViewSets and routers are common in web applications to provide easy and consistent access to data.
💼 Career
Understanding ViewSets and routers is essential for backend developers working with Django REST Framework to build scalable and maintainable APIs.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book in models.py with two fields: title as a CharField with max length 100, and author as a CharField with max length 100.
Django
Need a hint?

Remember to import models from django.db before defining the model.

2
Create the Book serializer
Create a serializer class called BookSerializer in serializers.py that uses serializers.ModelSerializer and includes all fields from the Book model.
Django
Need a hint?

Import serializers from rest_framework and create a Meta class inside your serializer.

3
Create the Book ViewSet
Create a ViewSet class called BookViewSet in views.py that inherits from viewsets.ModelViewSet. Set its queryset to all Book objects and its serializer_class to BookSerializer.
Django
Need a hint?

Import viewsets from rest_framework and create the ViewSet class with the correct attributes.

4
Register the ViewSet with a router
In urls.py, import DefaultRouter from rest_framework.routers and BookViewSet from views. Create a router instance, register the BookViewSet with the prefix 'books', and set urlpatterns to the router's URLs.
Django
Need a hint?

Import the router and the ViewSet, then register the ViewSet with the router and assign urlpatterns to router.urls.