python - With Django, what is the best practice way to add up a specific field on each object in a queryset? -


this how i'm getting total of each object.balance in queryset. feels wrong. there better way? (i'm struggling explain/write question see code below :) )

# models.py  ...  class foo(models.model):      ...      balance = models.decimalfield(         max_digits=10,         decimal_places=2,     )      ... ...  # utils.py  ...  def get_the_total():     objects = foo.objects.all()      total_balance = 0      object in objects:         total_balance += object.balance      return total_balance  ... 

there sum() built-in django:

foo.objects.aggregate(sum('balance')) 

Comments

Popular posts from this blog

javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -

javascript - How to synchronize the Three.js and HTML/SVG coordinate systems (especially w.r.t. the y-axis)? -

java - Reading data from multiple zip files and combining them to one -