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.
GenericAPIView is a more loaded version of APIView . It isn't really useful on its own but can be used to create reusable actions. Mixins are bits of common behavior. They're useless without GenericAPIView .
The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.
The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
ModelViewSet. The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list() , .retrieve() , .create() , .update() , .partial_update() , and .destroy() .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With