为模型的 属性 调用 Python 对象错误时超出最大递归深度

maximum recursion depth exceeded while calling a Python object error for property of a model

我的项目有问题。我的模型有一个总价,它会计算玩具车内所有产品的总和,这里是模型的 属性:

@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 self.total

self.discount 是订单的折扣,如果有,self.order_item 是订单内商品的相关名称。

所以问题是当我尝试从这个模型中获取总数时,它给我一个错误:

maximum recursion depth exceeded while calling a Python object

我从模型中获取总数的代码是:

i = order_id
amount = get_object_or_404(Order , id = i)

我还从 url 得到 order_id !

所以 os 这里错了。请帮帮我。

你不应该 return self.total,因为你会第二次获取 属性(因此它会继续获取 属性)。你应该 return 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)
    #       ↓ use total, not self.total
    return total