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
相关产品推荐
相关产品推荐

