0
0
Djangoframework~30 mins

Generic views in DRF in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Simple API with Generic Views in DRF
📖 Scenario: You are creating a small API for a bookstore. You want to list books and add new books easily using Django Rest Framework's generic views.
🎯 Goal: Build a simple API with a list and create endpoint for books using DRF generic views.
📋 What You'll Learn
Create a Book model with fields title and author
Create a serializer called BookSerializer for the Book model
Use DRF's generic views to create a view that lists all books and allows adding new books
Configure URL routing to connect the view to the path /books/
💡 Why This Matters
🌍 Real World
APIs like this let apps and websites get and add data easily, such as showing a list of books or adding new ones.
💼 Career
Knowing DRF generic views is important for backend developers building REST APIs quickly and cleanly.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with two fields: title as a CharField with max length 100, and author as a CharField with max length 100.
Django
Need a hint?

Think of a book as having a name and who wrote it. Use CharField for both.

2
Create the BookSerializer
Create a serializer class called BookSerializer that inherits from serializers.ModelSerializer. Inside, add a Meta class with model = Book and fields = ['id', 'title', 'author'].
Django
Need a hint?

Serializers help convert model data to JSON. Use ModelSerializer for easy setup.

3
Create the generic view for listing and creating books
Create a view class called BookListCreateView that inherits from generics.ListCreateAPIView. Set its queryset to Book.objects.all() and serializer_class to BookSerializer.
Django
Need a hint?

Generic views save time. Use ListCreateAPIView to list and add books.

4
Add URL routing for the book API
In your urls.py, import BookListCreateView and add a path 'books/' that points to BookListCreateView.as_view().
Django
Need a hint?

URLs connect your views to web addresses. Use path and as_view() for class-based views.