为了开始使用Django,我正在使用它为我的垒球队建立一个小站点,我们可以列出每个球员的统计数据。对于模型,我已经定义了2个表 - Player和Statline,其中Statline中的玩家是外键。
class Player(models.Model):
name = models.CharField(max_length=32)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
bats = models.CharField(max_length=1, choices=HANDED_CHOICES)
throws = models.CharField(max_length=1, choices=HANDED_CHOICES)
position = models.CharField(max_length=2, choices=POSITION_CHOICES)
pitches = models.CharField(max_length=1, choices=PITCHES_CHOICES)
hometown = models.CharField(max_length=32)
def __unicode__(self):
return self.name
class StatLine(models.Model):
season_name = models.CharField(max_length=12, choices=SEASON_CHOICES)
player = models.ForeignKey(Player)
at_bats = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
singles = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
doubles = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
triples = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
homeruns = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
runs = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
rbis = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
rboe = models.IntegerField(max_length=2, choices=NUMBER_CHOICES, default=0)
我要做的是做一个查询,我总结每个玩家的所有统计数据并按玩家分组。这样我每个赛季的所有统计数据都有一个运行记录。在SQL中,当我用PHP构建网站时,它是:
FROM Stats
INNER JOIN Players ON Players.player_id = Stats.player_id
WHERE season_name = 'Spring 2012'
GROUP BY Players.player_name
我对如何使用Django执行相同的查询感到困惑。任何帮助将不胜感激!
答案 0 :(得分:1)
Django's documentation about aggregation就足够了。
我不知道你为什么要按player_name
进行分组,因为你没有说明你想要选择哪些字段以及某处应该有聚合。是否可以为单个StatLine
提供多个Player
个对象?
如果你想要为每个玩家总结一个特定季节的所有本垒打,你可以使用这个片段:
from django.db.models import Sum
Player.objects.filter(
statline__season_name="Spring 2012"
).annotate(
sum_homeruns=Sum(statline__homeruns),
sum_abats=Sum(statline__abats),
sum_singles=Sum(statline__singles),
[…]
)
作为stated in the docs,filter()
和annotate()
的顺序非常重要。