Deleting resources in Django REST Framework involves handling single object deletions via standard HTTP DELETE methods and bulk multi-record deletions via custom ViewSet action endpoints.
Bulk Deletion ViewSet Action Code Example
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Item
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
# Custom action for bulk deletion: POST /api/items/bulk_delete/
@action(detail=False, methods=['post'])
def bulk_delete(self, request):
ids = request.data.get('ids', [])
if not ids:
return Response({"error": "No IDs provided"}, status=status.HTTP_400_BAD_REQUEST)
deleted_count, _ = Item.objects.filter(id__in=ids).delete()
return Response({"message": f"Successfully deleted {deleted_count} items."}, status=status.HTTP_200_OK)
Comments and corrections