使用Django,在查询集中的每个对象上添加特定字段的最佳实践方法是什么?

tee*_*ane 2 python django django-models django-queryset

这就是我目前在查询集中获得每个object.balance的总数.感觉不对.有没有更好的办法?(我很难解释/写这个问题,所以只看下面的代码:))

# 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

    for object in objects:
        total_balance += object.balance

    return total_balance

...
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 7

还有就是Sum()内置在Django的:

Foo.objects.aggregate(Sum('balance'))
Run Code Online (Sandbox Code Playgroud)