我正在尝试在查询中“加入”这4个模型。我的出发点是Team.id. 我试图让SkillRecord进入结果,但我完全迷失了。
class Team(models.Model):
user = models.ForeignKey(User)
id = models.IntegerField(primary_key=True, null=False, unique=True)
...
class Player(models.Model):
id = models.IntegerField(primary_key=True)
...
class Transfer(models.Model):
player = models.ForeignKey(Player)
seller = models.ForeignKey(Team, related_name='transfer_seller')
buyer = models.ForeignKey(Team, related_name='transfer_buyer')
date = models.DateTimeField()
...
class SkillRecord(models.Model):
player = models.ForeignKey(Player)
date = models.DateTimeField(default=datetime.datetime.now)
...
def list_players(request, teamid):
team = get_object_or_404(Team, id=teamid)
players_transfers = Transfer.objects.filter(buyer=team).select_related('player')
我不确定将SkillRecord模型引入游戏的下一步是什么。 我似乎缺乏这类问题的基本要点,所以我猜需要戳。
另外,请随时给我进一步的想法如何做到这一点,我或多或少地确定我也可以使用manytomanyfields左右解决整个转移事件。
非常感谢
答案 0 :(得分:0)
做出一些假设,每个玩家都有一个团队,所以我们可以添加。
class Player(models.Model):
team = models.ForeignKey(Team)
然后,如果你想要技能记录从那里开始
SkillRecord.objects.filter(player__team=team)
答案 1 :(得分:0)
要获取SkillRecord,您还需要添加related_name:
class SkillRecord(models.Model):
player = models.ForeignKey(Player, related_name='skills')
date = models.DateTimeField(default=datetime.datetime.now)
然后进行查询:
qt = Transfer.objects.filter(...).select_related('player').prefetch_related('player__skills')
然后像这样检索它们:
qt[0].player.skills.all()