将 pre_save 信号更改为 post_save?Django

Changing pre_save signal into post_save?Django

这是我的模型:

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 信号..

我该怎么做?我必须对函数进行哪些更改?

有什么想法吗?

谢谢

因为它是在实例 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)