gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:09:30 24 4
gpt4 key购买 nike

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

非常感谢您的提前帮助。

最佳答案

我会尝试这个,但我不确定它是否会适本地过滤每个玩家的分数。我不认为你的关系是完全规范化的——如果 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))

关于python - 如何编写Django模型以从多个表中获取记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com