Search code examples
djangodjango-modelsdjango-signals

Changing pre_save signal into post_save?Django


This are my models:

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)

I have done this in my pre_save signal:

@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

I want change the pre_save signal into post_save signal..

How do I do that?and what changes I have to make in the function?

Any idea?

Thank you


Solution

  • As it's operated after instance save method called you need to call it again in order to save the changes. But you need to use the update method instead of save in order to prevent save recursion.

    @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)