我是Django
的新手,我有以下问题,需要您的建议。 Django文档对我来说还不够,因为缺少示例
这里我们放.save()
函数:不知道我应该使用pre / post
def update_total(self):
self.total=self.cart.total+self.shipping_total
self.save()
在
postsave
函数中,我们没有放置save()
def postsave_order_total(sender,instance,created,*args,**kwargs):
if created:
print("just order created ")
instance.update_total()
post_save.connect(postsave_order_total,sender=orders)
并使用m2m信号放置.save函数,这是真的,如果这就是为什么我们没有在
.save()
或pre_save
中放置post_save()
的原因def cal_total(sender,instance,action,*args,**kwargs):
# print(action)
if action=="post_add" or action=="post_remove" or action=="post_clear":
prod_objs=instance.products.all()
subtotal=0
for prod in prod_objs:
subtotal+=prod.price
print(subtotal)
total=subtotal+10
instance.total=total
instance.subtotal=subtotal
instance.save()
m2m_changed.connect(cal_total, sender=cart.products.through)
在M2M信号中,为什么指定操作:
if action=="post_add" or action=="post_remove" or action=="post_clear"
同样在更新中,我没有使用
save()
。qs = orders.objects.filter(cart=instance.cart,active=instance.active).exclude(billing_profile=instance.billing_profile)
if qs.exists():
qs.update(active=False)
最佳答案
pre_save
在保存模型之前,post_save
在保存模型之后。
在此之前,您要先处理信息,例如要确保数据在保存之前是有效的,或者在保存模型后附加文件后保存。