1

I'm struggling to try and figure out why a post_save function is returning:

Exception Type:     RuntimeError
Exception Value:    maximum recursion depth exceeded

Here is my code:

#post save functions of the order
def orderPs(sender, instance=False, **kwargs):
    if instance.reference is None:
        instance.reference = str(friendly_id.encode(instance.id))

    #now update the amounts from the order items
    total = 0
    tax = 0
    #oi = OrderItem.objects.filter(order=instance)
    #for i in oi.all():
    #    total += i.total
    #    tax += i.total_tax

    instance.total = total
    instance.tax = tax
    instance.save()


#connect signal
post_save.connect(orderPs, sender=Order)

I've commented out the order items code for now.

instance.total and instance.tax are model decimal fields.

It seems like the post_save function is in an endless loop, not sure why as I've used the same format for all of my post_save functions.

Any ideas?

1 Answer 1

1

You are calling instance.save() in your post save signal thus triggering it recursively.

All your edited fields in this signal receiver are quite simply derived from other values already stored in the database thus creating redundancies. This is usually not a good idea. Write properties or cached properties instead:

from django.db.models import Sum
from django.utils.functional import cached_property

class Order(model.Model):
    ...
    @cached_property       # or @property
    def total(self):
         return self.orderitem_set.aggregate(total_sum=Sum('total'))['total_sum']

    # do the same with tax
Sign up to request clarification or add additional context in comments.

5 Comments

doh, how do I save the new values since the reference is based off the id? Also, the order items aren't created until there is an order object?
thanks for the reply.. quick question... if I remove all but the reference generation from my post_save function and call "instance.save()" - is it still going to recursively call?
yes. the instance.save() is the only reason for the recursion and this doesn't depend on whether actual fields have been altered.
found this solution fyi: old.marconijr.com/content/…
Thanks! Acutally I thought about that, but in your case that's just fighting the symptoms. You should really try to avoid redundancies in databases!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.