Python Django最大递归深度超过十进制
我正在努力尝试并弄清楚post_save函数返回的原因:Python Django最大递归深度超过十进制,python,django,Python,Django,我正在努力尝试并弄清楚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: in
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函数都使用了相同的格式
有什么想法吗?您正在post save信号中调用
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
您正在post save信号中调用
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()
是递归的唯一原因,这并不取决于实际字段是否已更改。找到此解决方案仅供参考:谢谢!我确实想过,但对你来说,这只是对抗症状。您应该真正尝试避免数据库中的冗余!doh,既然引用是基于id的,我如何保存新值?此外,只有在存在订单对象时才会创建订单项目?感谢您的回复。。快速提问。。。如果我从post_save函数中删除除引用生成之外的所有内容并调用“instance.save()”—它是否仍将递归调用?是的。instance.save()
是递归的唯一原因,这并不取决于实际字段是否已更改。找到此解决方案仅供参考:谢谢!我确实想过,但对你来说,这只是对抗症状。您应该真正尝试避免数据库中的冗余!