Skip to content

Django REST ViewSet Action Fix

DodaTech Updated 2026-06-24 2 min read

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 @action for extra endpoints instead of wiring separate views.
  • Set detail=True for single-object operations, detail=False for collection operations.
  • Register with a DefaultRouter to get automatic URL patterns.

Common Mistakes with rest viewset action

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. 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

### What's the difference between detail and list actions?

Detail actions operate on a single object and include {pk} in the URL. List actions operate on the collection.

Can I use multiple HTTP methods on one action?

Yes: @action(detail=True, methods=['get', 'post']). DRF dispatches to the same method for both.

How do I set a custom URL path?

Use url_path: @action(detail=True, methods=['post'], url_path='mark-approve').

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro