I am Trying to get total but i don't know why i am not getting the total and i have the code of models.py and it's output
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
table_num = models.CharField(max_length=50)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def total(self):
total = 0
for order_item in self.items.all():
total = order_item.get_total_item_price()
return total
CodePudding user response:
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].
CodePudding user response:
Python Typo. Indentation error. It should be
for order_item in self.items.all():
total = order_item.get_total_item_price()
return total