Home > OS >  maximum recursion depth exceeded while calling a Python object error for property of a model
maximum recursion depth exceeded while calling a Python object error for property of a model

Time:11-08

There is a problem with my project . I have a total price in my model and its going to sum all the products inside toyr cart and here is the property for model :

@property
def total(self):
    total = sum( i.price() for i in self.order_item.all())
    if self.discount:
        discount_price = (self.discount / 100) * total
        return int(total - discount_price)
    return self.total

self.discount is the discount of the order if it had and self.order_item is the related name for the items inside the order.

so the problem is when i try to get the total from this model , it give me an error :

maximum recursion depth exceeded while calling a Python object

And my code to get the total from the model is :

i = order_id
amount = get_object_or_404(Order , id = i)

Also i get the order_id from the url !

So what os wrong here . Hepl me please .

CodePudding user response:

You should not return self.total, since then you fetch the property a second time (and thus it will keep fetching the property). You should return the total, so:

@property
def total(self):
    total = sum( i.price() for i in self.order_item.all())
    if self.discount:
        discount_price = (self.discount / 100) * total
        return int(total - discount_price)
    #       ↓ use total, not self.total
    return total
  • Related