How would I override the perform_destroy method in

2020-08-11 10:36发布

问题:

DRF currently has functionality that throws a 404 if an object doesn't exist in the db. For example

Request: /delete/1234
Response: 204 (success)
Request 2: /delete/1234
Response: 404 (not found)

This logic is very problematic for my mobile apps and i would like to change it so that I override the 404-not-found functionality. In other words, I want my request to be idempotent. For example:

Request: /delete/1234
Response: 204 (success)
Request 2: /delete/1234
Response: 204 (success)

I've been looking at the docs but i'm not really sure how to override the get_object_or_404 functionality.

回答1:

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 ExampleDestoryViewset(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)


回答2:

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

class ExampleDestoryViewset(viewset.ModelViewSet):
    queryset = # queryset
    serializer_class = # serializer class

    def get_queryset(self):
        # write custom code

    def perform_destroy(self, instance): 
        # write custom code