ViewSets
ViewSets allow you to combine the logic for multiple related views into a single class. Instead of defining get(), post(), etc., you define actions like list(), retrieve(), create(), and destroy().
Using ModelViewSet
The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions by mixing in the behavior of the various mixin classes.
python
from rest_framework import viewsets
from .models import User
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializerCustom Actions
You can add custom endpoints to a ViewSet using the @action decorator.
python
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@action(detail=True, methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
# Custom logic here...
return Response({'status': 'password set'})detail=Trueroutes to/users/{pk}/set_password/(acts on a single object).detail=Falseroutes to/users/set_password/(acts on a collection of objects).
