我在我的模型中尝试了这个答案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_保存信号,当它与信号中的条件匹配时,就会被递归调用。
有人告诉我我的代码有什么问题吗?
谢谢你
1条答案
按热度按时间lb3vh1jj1#
这是有点晚了,但它也可能帮助其他人。相反,你可以添加dispatch_uid=“identifier”到信号中,它会工作得很好。
或
文档:https://docs.djangoproject.com/en/4.1/topics/signals/#preventing-duplicate-signals