Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do total on Django models.p

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

enter image description here

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading