class Game(models.Model):
total_players = models.IntegerField(max_length=10)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Players(models.Model):
game = models.ForeignKey(Game, related_name='players')
name = models.CharField(max_length=10, verbose_name="Player Name")
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Score(models.Model):
game = models.ForeignKey(Game)
name = models.ForeignKey(Players, related_name='scores')
score = models.IntegerField(max_length=10)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
如何使用Django模型编写此查询?
select p.name, sum(s.score) as total_score
from game g, players p, score s
where g.id=17 and g.id = p.game_id and p.id = s.name_id
group by p.name
非常感谢您的帮助。
答案 0 :(得分:0)
我会尝试这个,但我不确定是否会适当地将分数过滤到每个玩家的分数。我不认为您的关系已完全正常化 - 如果Score
与Players
多对一,而Players
与Game
是多对一的,那么您通常不会game
跟踪Score
作为独立的FK。每个Players
行是否真的只存在于一个游戏中?
from django.db.models import Sum
Game.objects.filter(id=17).values(players__name).annotate(total_score=Sum(players__scores_score))