0
0
Djangoframework~5 mins

Generic views in DRF in Django

Choose your learning style9 modes available
Introduction

Generic views in Django REST Framework help you quickly create common API endpoints without writing repetitive code.

When you want to list all items of a model and create new ones easily.
When you need to retrieve, update, or delete a single item by its ID.
When you want to build simple CRUD (Create, Read, Update, Delete) APIs fast.
When you want to avoid writing the same code for common API actions.
When you want to keep your code clean and easy to maintain.
Syntax
Django
from rest_framework import generics

class MyModelListCreateView(generics.ListCreateAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Use queryset to tell the view which data to work with.

Use serializer_class to define how data is converted to and from JSON.

Examples
This view lists all books and allows creating new books.
Django
class BookListCreateView(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
This view lets you get, update, or delete a single book by its ID.
Django
class BookDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
This view only lists all authors without create or update options.
Django
class AuthorListView(generics.ListAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
Sample Program

This simple API view lets users see all books and add new books using HTTP GET and POST requests.

Django
from rest_framework import generics
from myapp.models import Book
from myapp.serializers import BookSerializer

class BookListCreateView(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
OutputSuccess
Important Notes

Generic views save time but you can customize them by overriding methods if needed.

Always define queryset and serializer_class for generic views to work.

Use URL patterns with path converters like <int:pk> to connect detail views.

Summary

Generic views provide ready-made classes for common API tasks.

They reduce repeated code and speed up API development.

Use them with a queryset and serializer to quickly build CRUD endpoints.