Django REST ViewSet Action Fix
In this tutorial, you'll learn about Django REST ViewSet Action Fix. We cover key concepts, practical examples, and best practices.
The Problem
Standard ViewSets provide list/create/retrieve/update/destroy. When you need extra endpoints — like activating a user, approving an order, or generating a report — you need custom actions.
Quick Fix
Wrong — separate APIView or urlpatterns
# urls.py
urlpatterns = [
path('orders/', OrderViewSet.as_view({'get': 'list'})),
path('orders/<pk>/approve/', approve_order), "# Separate view", no ViewSet integration
]
Output: Works but breaks the ViewSet pattern. No Browsable API integration, no router support.
Correct — @action decorator
from rest_framework.decorators import action
from rest_framework.response import Response
class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderSerializer
@action(detail=True, methods=['post'])
def approve(self, request, pk=None):
order = self.get_object()
order.status = 'approved'
order.save()
return Response({'status': 'approved'})
Output: Endpoint at /orders/{pk}/approve/. Automatically routed by the router.
Detail vs list actions
@action(detail=True, methods=['post']) # /orders/{pk}/approve/
@action(detail=False, methods=['get']) # /orders/recent/
Custom action with custom serializer
@action(detail=False, methods=['get'])
def recent(self, request):
orders = self.get_queryset().filter(created_at__gte=one_day_ago)
serializer = OrderSummarySerializer(orders, many=True)
return Response(serializer.data)
Action with permission and throttle
@action(detail=True, methods=['post'],
permission_classes=[IsAdminUser],
throttle_classes=[BurstRateThrottle])
def refund(self, request, pk=None):
...
Prevention
- Always use
@actionfor extra endpoints instead of wiring separate views. - Set
detail=Truefor single-object operations,detail=Falsefor collection operations. - Register with a
DefaultRouterto get automatic URL patterns.
Common Mistakes with rest viewset action
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro