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

Django模型total属性调用报maximum recursion depth exceeded错误如何解决

问题根因

你定义的total属性方法存在无限递归逻辑:
无折扣分支的返回值写为return self.total,而self.total本身就是当前这个被@property装饰的方法,调用时会再次执行该方法的逻辑,一直循环直到超过Python默认的递归深度上限,触发你遇到的报错。
获取实例时触发报错是因为Django ORM加载实例的过程中,如果有逻辑(比如模型的__str__方法、序列化逻辑、字段校验逻辑等)访问了total属性,就会触发这段递归代码,和你写的get_object_or_404代码本身无关。

修复方案

将无折扣分支的返回值替换为前面计算好的局部变量total即可,修改后的代码如下:

@property
def total(self):
    total = sum( i.price() for i in self.order_item.all())
    if self.discount:
        discount_price = (self.discount / 100) * total
        return int(total - discount_price)
    return total

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:04