Junior — Middle
What are the components and structure of ViewSet in Django REST Framework?
sobes.tech AI
Answer from AI
A ViewSet in Django REST Framework is a class that combines the logic for handling HTTP requests for a set of related actions (e.g., CRUD) on a model.
Main components of a ViewSet:
- queryset — the set of model objects that the ViewSet operates on.
- serializer_class — the serializer class that converts model objects to JSON and back.
- action methods — methods corresponding to HTTP operations, such as
list(),create(),retrieve(),update(),destroy().
ViewSet allows reducing code duplication by automatically linking URLs to methods via routers.
Example of a simple ViewSet:
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
Here, ModelViewSet provides a full set of actions for the Product model.