Issue
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.
Solution
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)
Answered By - Tevin Joseph K O
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.