我如何在Django rest框架中覆盖perform_destroy方法? [英] How would I override the perform_destroy method in django rest framework?

查看:321
本文介绍了我如何在Django rest框架中覆盖perform_destroy方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DRF当前具有的功能可以在数据库中不存在对象时抛出404。例如

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)

此逻辑对我来说很成问题移动应用程序,我想对其进行更改,以便覆盖404(未找到)功能。换句话说,我希望我的要求是幂等的。例如:

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)

我一直在寻找docs,但我不太确定如何重写 get_object_or_404 功能。

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

推荐答案

我相信,如果没有要删除的对象,理想情况下,它应该像DRF一样返回404。

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)

这篇关于我如何在Django rest框架中覆盖perform_destroy方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆