如何防止django post_保存信号中的递归?

rqdpfwrv  于 2022-12-05  发布在  Go
关注(0)|答案(1)|浏览(135)

我在我的模型中尝试了这个答案https://stackoverflow.com/a/28369908/9902571,并完成了以下操作:-

from functools import wraps

def prevent_recursion(func):

        @wraps(func)
        def no_recursion(sender, instance=None, **kwargs):

            if not instance:
                return

            if hasattr(instance, '_dirty'):
                return

            func(sender, instance=instance, **kwargs)

            try:
                instance._dirty = True
                instance.save()
            finally:
                del instance._dirty

        return no_recursion

我的模型:

class Journal(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    company         = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname')
    date            = models.DateField(default=datetime.date.today)
    voucher_id      = models.PositiveIntegerField(blank=True,null=True)
    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,null=True)
    credit          = models.DecimalField(max_digits=10,decimal_places=2,null=True)

我的信号:

@receiver(post_save, sender=journal)
@prevent_recursion
def pl_journal(sender, instance, created, **kwargs):
    if created:
        if instance.by.group1_Name.group_Name == 'Indirect Expense':
            Journal.objects.update_or_create(user=instance.user,company=instance.company,date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,to=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first(),debit=instance.debit,credit=instance.credit)

但是,在创建日志对象时,maximum recursion depth exceeded while calling a Python object的RecursionError仍然会出现。
我想传递相同模型(Journal)的post_保存信号,当它与信号中的条件匹配时,就会被递归调用。
有人告诉我我的代码有什么问题吗?
谢谢你

lb3vh1jj

lb3vh1jj1#

这是有点晚了,但它也可能帮助其他人。相反,你可以添加dispatch_uid=“identifier”到信号中,它会工作得很好。

post_save.connect(function_name, sender=Model, dispatch_uid="identifier")

@receiver(post_save, sender=Model, dispatch_uid="identifier")

文档:https://docs.djangoproject.com/en/4.1/topics/signals/#preventing-duplicate-signals

相关问题