[Answered ]-How to do total on Django models.py

1👍

You immediately return the result after the first iteration, you should use:

def total(self):
    total = 0 
    for order_item in self.items.all():
        total += order_item.get_total_item_price()
    return total

or with a sum(…):

def total(self):
    return sum(order_item.get_total_item_price() for order_item in self.items.all())

But the best is probably to work with an .aggregate(…) [Django-doc].

0👍

Python Typo. Indentation error. It should be

    for order_item  in self.items.all():
        total += order_item.get_total_item_price()
    return total

Leave a comment