通过相关对象链接查询

时间:2015-07-22 17:50:41

标签: django

考虑如下情况:

from django.db import models

class Player(models.Model):
    playername = models.CharField()

class Team(models):
    teamname = models.CharField()

class Members(models):
    player = models.ForeignKey(Player)
    team = models.ForeignKey(Team)

class Division(models):
    divname = models.CharField()  

class DivisionTeam(models):
    division = models.ForeignKey(Division)
    team = models.ForeignKey(Team)

如何列出分区ID = 5的所有不同玩家?我查看了Q和F表达式,但我并不是在寻找一组复杂的或者是。我想知道是否有一种链接一些object1_set.object2_set.all()类型结构的方法,或者我是否设置了一个嵌套循环来构建对象(通过上下文传递给模板),最终为{% for p in players %}类型循环在模板中。 div id作为请求变量传递。

2 个答案:

答案 0 :(得分:1)

您最好先简化模型。我认为您不需要MembersDivisionTeam模型:

from django.db import models

class Division(models):
    divname = models.CharField()

class Team(models):
    teamname = models.CharField()
    division = models.ForeignKey(Division)

class Player(models.Model):
    playername = models.CharField()
    team = models.ManyToManyField(Team)

然后,您的查询就是:

Player.objects.filter(team__division__pk=5)

如果您每个评论都需要中间模型,则应使用through关系:

# Uses "Salary" as an example intermediate model.
class Player(models.Model):
    playername = models.CharField()
    team = models.ManyToManyField(Team, through="Salary")

class Salary(models.Model):
    value = models.IntegerField()
    player = models.ForeignKey(Player)
    team = models.ForeignKey(Team)

答案 1 :(得分:1)

你可以这样做:

players = Player.objects.filter(members__team__divisionteam__division_id=5).distinct()

当然,正如其他答案所示,您的模型可以简化(使用ManyToMany而不是明确管理它)