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 - ScrollTo Effect (href to div) -

javascript - ng-class not responding to change in model in Angular? -

javascript - document.registerElement extending HTMLInputElement prototype while using custom tag name to avoid implicit browser style -