You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DRF自定义perform_destroy返回204无内容 如何输出自定义响应

问题原因

你遇到的返回异常是Django REST Framework(DRF)的默认逻辑导致的:DestroyModelMixin 内置的destroy()方法不会接收perform_destroy()的返回值,它的默认实现是调用完perform_destroy()后直接返回固定的204无内容响应,你在perform_destroy()中返回的自定义Response会被直接丢弃。

默认destroy()方法的核心逻辑参考:

def destroy(self, request, *args, **kwargs):
    instance = self.get_object()
    self.perform_destroy(instance) # 仅调用方法,不处理返回值
    return Response(status=status.HTTP_204_NO_CONTENT) # 固定返回204

解决方法

不需要自定义perform_destroy(),直接在你的视图类中重写完整的destroy()方法,把你的业务逻辑写在该方法内即可,示例代码如下:

def destroy(self, request, *args, **kwargs):
    instance = self.get_object()
    force = request.data.get('force', None)
    resp = {}
    
    # 原校验逻辑
    has_production_record = Processingstepstatus.objects.filter(orderfile__order=instance).exists()
    if has_production_record and not force:
        raise serializers.ValidationError({
            "message": f"Order already in production and can't be canceled cost-free. Perform Delete Request with parameter \"force:True\" to cancel and assume the costs of {instance.currentcosts}€" 
        })
    
    if has_production_record and force:
        resp['invoice'] = "Placeholdervalue"
    
    instance.canceled = True
    instance.save()
    resp['message'] = "Successfully canceled your order."
    return Response(resp, status=status.HTTP_200_OK)

内容的提问来源于stack exchange,提问作者Rune

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:39:04