我在模型中尝试了此答案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_save信号,当匹配信号中的条件时,将递归调用该信号。
有人告诉我我的代码有什么问题吗?
谢谢