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
Post a Comment