将pre_save信号更改为post_save?Django

问题描述 投票:0回答:1

这是我的模特:

class Purchase(models.Model):
  Total_Purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True)


class Stock_Total(models.Model):
    purchases   = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') 
    stockitem   = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') 
    Total_p     = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)

我在pre_save信号中完成了这个:

@receiver(pre_save, sender=Purchase)
def user_created1(sender,instance,*args,**kwargs):
        total = instance.purchasetotal.aggregate(the_sum=Coalesce(Sum('Total_p'), Value(0)))['the_sum']
        instance.Total_Purchase = total

我想将pre_save信号更改为post_save信号..

我该怎么做?我在功能中需要做些什么改变?

任何的想法?

谢谢

django django-models django-signals
1个回答
1
投票

因为它在实例save方法调用之后运行,你需要再次调用它以保存更改。但是你需要使用update方法而不是save来防止save递归。

@receiver(post_save, sender=Purchase)
def user_created1(sender,instance, created=False, *args,**kwargs):
    total = instance.purchasetotal.aggregate(the_sum=Coalesce(Sum('Total_p'), Value(0)))['the_sum']
    Purchase.objects.filter(pk=instance.pk).update(Total_Purchase=total)
© www.soinside.com 2019 - 2024. All rights reserved.