Create, Retrieve, Update, Delete APIs
DRF Generic Views and ModelViewSet CRUD
Building enterprise APIs often involves writing identical CRUD endpoints across dozens of models. Writing raw APIView classes for every table introduces repetitive boilerplate. Django REST Framework solves this through Generic Views and ModelViewSet, delivering complete CRUD operations with minimal code.
1. DRF's Concrete Generic Views
DRF pairs GenericAPIView with CRUD mixins to provide ready-to-use concrete generic views:
| Generic View | Allowed Methods | Purpose |
|---|---|---|
ListAPIView | GET | Read a collection of resources. |
CreateAPIView | POST | Create a new resource. |
ListCreateAPIView | GET, POST | Read collection and create new items. |
RetrieveAPIView | GET | Read single resource by lookup field. |
UpdateAPIView | PUT, PATCH | Update single resource. |
DestroyAPIView | DELETE | Delete single resource. |
RetrieveUpdateDestroyAPIView | GET, PUT, PATCH, DELETE | Complete single-resource management. |
2. The Complete CRUD Controller: ModelViewSet
Why write two separate generic views when a single ModelViewSet handles everything?
3. Dynamic Serializers per Action
In enterprise applications, list views often need summary fields, while retrieve and create views require detailed or write-only fields. Override get_serializer_class():
4. Lifecycle Hooks for Business Logic
Generic views and ViewSets provide dedicated hooks to execute business logic without hacking method overrides:
perform_create(serializer): Called before saving a new instance.perform_update(serializer): Called before updating an instance.perform_destroy(instance): Called before deleting an instance (ideal for soft deletes).
Practice Quiz
Endpoints for Models
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Function-Based Views & Class-Based Views | Endpoints for Models |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.