Junior — Middle
Can you explain what the ModelViewSet class is and how it is used in Django REST Framework?
sobes.tech AI
Answer from AI
In Django REST Framework (DRF), the ModelViewSet class provides a convenient way to create a set of standard CRUD operations for a database model with minimal code.
ModelViewSet combines the functionality of several classes:
- Listing objects (list)
- Retrieving a single object (retrieve)
- Creating an object (create)
- Updating an object (update, partial_update)
- Deleting an object (destroy)
To use ModelViewSet, you need to define a serializer and queryset, for example:
from rest_framework import viewsets
from myapp.models import Book
from myapp.serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
After that, you can connect the BookViewSet to routes using DRF's router, providing a full REST API for the Book model without additional code.
This greatly simplifies API development, allowing quick creation of standard data operations.