Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I override the perform_destroy method in django rest framework?

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.

like image 993
Kamilski81 Avatar asked Sep 10 '15 23:09

Kamilski81


People also ask

What is the difference between APIView and GenericAPIView?

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 .

What is QuerySet in Django REST Framework?

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.

What is renderers in Django REST Framework?

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.

What is ModelViewSet in Django REST Framework?

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


1 Answers

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)
like image 199
Tevin Joseph K O Avatar answered Sep 20 '22 21:09

Tevin Joseph K O