Django:我可以为同一操作执行两个预保存信号吗?

时间:2018-10-12 06:55:07

标签: django django-models django-signals

我可以在django中执行两个预保存信号以进行相同的操作,只是在两种情况下发件人都会有所不同...

这是我的模特

   class Ledger1(models.Model):
        creation_Date = models.DateField()
        name = models.CharField(max_length=32)
        group1_Name = models.ForeignKey(Group1,on_delete=models.CASCADE,blank=True,null=True)
        Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2,blank=True)
        Closing_balance = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True)

   class Journal(models.Model):
        Date = models.DateField()
        By = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers')
        To = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers')
        Debit = models.DecimalField(max_digits=10,decimal_places=2)
        Credit = models.DecimalField(max_digits=10,decimal_places=2)

这是我之前所做的:

@receiver(pre_save, sender=Ledger1)
def update_user_closing_balance(sender,instance,*args,**kwargs):
    debit = instance.Debitledgers.aggregate(debit=Sum('Debit'))['debit']
    credit = instance.Creditledgers.aggregate(credit=Sum('Credit'))['credit']
    instance.Closing_balance = instance.Opening_Balance + debit - credit

我想做一个类似的预保存信号,但是发件人将是日记...并且在django中我可以有两个具有相同功能的信号吗?

我的意思是说,更新分类帐时,我已经完成的期末余额将自动更新...

但是我也想做一些事情,例如更新日记帐时,期末余额也会更新...

有人知道吗?

1 个答案:

答案 0 :(得分:1)

这将触发相关Ledger1模型的pre_save

from django.db.models.signals import post_save
@receiver(post_save, sender=Journal)
def trigger_pre_save(sender, instance, *args, **kwargs):
        instance.By.save()  # trigger pre_save for By Ledger
        # or
        # post_save.send(Ledger1, instance=instance.By, created=False)
        instance.To.save() # trigger pre_save for To Ledger
        # or
        # post_save.send(Ledger1, instance=instance.To, created=False)