简体   繁体   English

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

[英]How to write Django model to get record from multiple tables?

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)

How do I write this query with Django models? 如何使用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 

Thank you so much for your help in advance. 非常感谢您的提前帮助。

I'd try this, but I'm not sure offhand if it will appropriately filter the scores to those for each player. 我会尝试一下,但是我不确定它是否可以适当地将分数过滤为每个玩家的分数。 I don't think your relationships are fully normalized - if Score is many-to-one for Players , and Players is many-to-one with Game , you wouldn't normally track game as an independent FK on Score . 我不认为你们的关系是完全规范化-如果Score是多到一个Players ,而Players是多到一个与Game ,你通常不会追踪game作为一个独立的FK的Score Can each Players row really exist only for a single game? 每个Players行是否真的只能存在于一个游戏中?

from django.db.models import Sum
Game.objects.filter(id=17).values(players__name).annotate(total_score=Sum(players__scores_score))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM