【问题标题】:Django maximum recursion depth exceeded decimalDjango最大递归深度超过十进制
【发布时间】:2012-06-09 01:49:30
【问题描述】:

我正在努力尝试找出 post_save 函数返回的原因:

Exception Type:     RuntimeError
Exception Value:    maximum recursion depth exceeded

这是我的代码:

#post save functions of the order
def orderPs(sender, instance=False, **kwargs):
    if instance.reference is None:
        instance.reference = str(friendly_id.encode(instance.id))

    #now update the amounts from the order items
    total = 0
    tax = 0
    #oi = OrderItem.objects.filter(order=instance)
    #for i in oi.all():
    #    total += i.total
    #    tax += i.total_tax

    instance.total = total
    instance.tax = tax
    instance.save()


#connect signal
post_save.connect(orderPs, sender=Order)

我现在已经注释掉了订单商品代码。

instance.total 和 instance.tax 是模型十进制字段。

似乎 post_save 函数处于无限循环中,不知道为什么,因为我对所有 post_save 函数都使用了相同的格式。

有什么想法吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您在保存后的信号中调用instance.save(),从而递归地触发它。

    您在此信号接收器中编辑的所有字段都非常简单地从已经存储在数据库中的其他值派生而来,从而产生了冗余。这通常不是一个好主意。改为写入属性或缓存属性:

    from django.db.models import Sum
    from django.utils.functional import cached_property
    
    class Order(model.Model):
        ...
        @cached_property       # or @property
        def total(self):
             return self.orderitem_set.aggregate(total_sum=Sum('total'))['total_sum']
    
        # do the same with tax
    

    【讨论】:

    • doh,由于引用基于 id,我如何保存新值?另外,在有订单对象之前不会创建订单项目?
    • 感谢您的回复.. 快速提问...如果我从我的 post_save 函数中删除除参考生成之外的所有内容并调用“instance.save()” - 它还会递归调用吗?
    • 是的。 instance.save() 是递归的唯一原因,这不取决于实际字段是否已更改。
    • 找到这个解决方案仅供参考:old.marconijr.com/content/…
    • 谢谢! Acutally 我想过这一点,但在你的情况下,这只是对抗症状。您真的应该尽量避免数据库中的冗余!
    猜你喜欢
    • 2013-03-03
    • 2017-08-09
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2017-11-05
    • 2013-11-30
    • 2020-12-13
    相关资源
    最近更新 更多