如何编写Django模型以从多个表中获取记录?

时间:2013-12-07 23:41:40

标签: python mysql django join django-models

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 

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我会尝试这个,但我不确定是否会适当地将分数过滤到每个玩家的分数。我不认为您的关系已完全正常化 - 如果ScorePlayers多对一,而PlayersGame是多对一的,那么您通常不会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))