Niladry Kar
Niladry Kar

Reputation: 1203

Django: RecursionError: maximum recursion depth exceeded

I am getting a runtime error in django while saving a certain model.

I want to save the model with two instances

So I have done the following:


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,
        )

The problem is in the following line of code in my signal:

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

Anyone have any idea why this error is happening?

Is there any way to solve it?

Thank you

Upvotes: 1

Views: 3365

Answers (1)

AKX
AKX

Reputation: 169308

You have a pre_save signal receiver for a model that ends up managing the same model, so you get something like this:

  1. journal.save() is called
  2. pl_journal(sender=Journal, instance=journal) is called
  3. Journal.objects.update_or_create(...) is (possibly) called
  4. .update_or_create() calls .save() on the Journal instance it updates or creates, so go back to step 1.

You thus have an infinite recursion happening, which Python limits to the maximum recursion depth and raises that exception.

Upvotes: 2

Related Questions