[Fixed]-How would I override the perform_destroy method in django rest framework?

25๐Ÿ‘

โœ…

I believe, if there is no object to delete, ideally it should return 404 as DRF does.

For your requirement the following code will do the trick:

from rest_framework import status,viewsets
from rest_framework.response import Response
from django.http import Http404

 class ExampleDestroyViewset(viewset.ModelViewSet):
    def destroy(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)

6๐Ÿ‘

To implement the custom functionality you need to override get_object() method in the viewset. Follow the links get_object and perform_destroy

class ExampleDestroyViewset(viewset.ModelViewSet):
    queryset = # queryset
    serializer_class = # serializer class
    
    def get_queryset(self):
        # write custom code

    def perform_destroy(self, instance): 
        # write custom code
๐Ÿ‘คSeenu S

Leave a comment