如何用Django计算平均值?

时间:2015-02-19 13:32:42

标签: python django

在我的会员班中,我有“胜利”和“失败” - 如何计算这两个领域的平均赢率?

我可以手动插入一个平均字段并自己进行计算,但我确信Django可以为我做到这一点。有什么想法吗?

注意:我想要每个成员的平均值,而不是整体平均值

3 个答案:

答案 0 :(得分:6)

您可以在django查询中使用聚合和平均值。

假设您的模型成员字段名称获胜损失

from django.db.models import Avg

Member.objects.aggregate(Avg('wins'))
Member.objects.aggregate(Avg('losses'))

答案 1 :(得分:2)

You simply using values(), aggregate() and function Avg() and F().

Let's assume You have Model like this:

class Member(models.Model):
    nickname = models.CharField(max_length=16, unique=True)

class MatchResult(models.Model):
    member = models.ForeignKey('Member')
    wins = models.IntegerField()
    losses = models.IntegerField()

Now You can aggregate those using this syntax (look at __ double underscore notation):

MatchResult.objects.values(
    'username_id', 
    'username__nickname', 
    'wins',
    'losses'
).aggregate(
    user_id=F('username_id'),
    nickname=F('username__nickname'),
    avg_wins=Avg('wins'),
    avg_losses=Avg('losses')
)

Please refer to documentation.

Hint: Order of annotate and filter clauses is IMPORTANT.

答案 2 :(得分:0)