Django:RecursionError:超过最大递归深度

时间:2019-03-06 12:29:33

标签: django django-models django-signals

在保存某个模型时,我在django中遇到运行时错误。

我想用两个实例保存模型

所以我做了以下事情:


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"
    )
    counter = models.IntegerField(blank=True, null=True)
    urlhash = models.CharField(max_length=100, null=True, blank=True, unique=True)
    date = models.DateField(default=datetime.date.today)
    voucher_id = models.PositiveIntegerField(blank=True, null=True)
    voucher_type = models.CharField(max_length=100, blank=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)
    narration = models.TextField(blank=True)


@receiver(pre_save, sender=Journal)
def pl_journal(sender, instance, *args, **kwargs):
    if (
        instance.debit != None
        or instance.credit != None
        or 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,
            dredit=instance.credit,
        )

问题出在我的信号中的以下代码行中:

to=ledger1.objects.filter(user=instance.user,company=instance.company,name__icontains='Profit & Loss A/c').first()

任何人都知道为什么会发生此错误吗?

有什么办法解决吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您有一个用于模型的pre_save信号接收器,最终可以管理相同的模型,所以您得到的是这样的东西:

  1. journal.save()被称为
  2. pl_journal(sender=Journal, instance=journal)被称为
  3. Journal.objects.update_or_create(...)被称为
  4. .update_or_create()在它更新或创建的Journal实例上调用.save(),因此回到步骤1。

因此,您将发生无限次递归,Python将其限制为最大递归深度并引发该异常。

相关问题