Junior — Middle
Can you explain the concept of ViewSet and its role in developing REST API 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 multiple HTTP request types (GET, POST, PUT, DELETE, etc.) for a specific resource in one place. It simplifies creating REST APIs by allowing you to not write separate methods for each action but use ready-made implementations.
Role of ViewSet:
- Provides standard actions: list (list objects), retrieve (get a single object), create, update, partial_update, destroy.
- Enables rapid development of CRUD interfaces without code duplication.
- Works with routers to automatically generate URLs for all operations.
Example of a simple ViewSet:
from rest_framework import viewsets
from myapp.models import Product
from myapp.serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
Here, ModelViewSet provides a full set of CRUD operations for the Product model, significantly speeding up API development.