通过ForeignKey向后和向前过滤

时间:2011-03-21 05:31:19

标签: django foreign-keys

我有3个模型类:

class Team(models.Model):
    name = models.CharField(max_length=100, default="", blank=True, null=True)
    number = models.IntegerField() 

class Position(models.Model):
    match = models.ForeignKey('Match')
    color = models.CharField(max_length=5)
    number = models.IntegerField()

    team = models.ForeignKey('Team')

class Match(models.Model):
    type = models.CharField(max_length=3)
    number = models.IntegerField()

    red_score = models.IntegerField(default=0)
    blue_score = models.IntegerField(default=0)

    match_events = models.TextField(max_length=1000)

现在使用模型,我如何获得团队赢得的匹配列表(即如果团队属于红色位置,如果其匹配具有red_score>则将其添加到列表中; blue_score)

很抱歉,如果这令人困惑。如果您有任何具体问题,我可以尝试澄清。

谢谢!

1 个答案:

答案 0 :(得分:2)

最简单的方法:

Match.objects.filter(position__color='red', red_score__gt=F('blue_score'))

您可能希望将Position模型移到底部,以从外键相关模型名称中删除撇号。

这也是使用ManyToMany关系的非常好的例子:

class Team(models.Model):
    name = models.CharField(max_length=100, default="", blank=True, null=True)
    number = models.IntegerField()


class Match(models.Model):
    type = models.CharField(max_length=3)
    number = models.IntegerField()
    red_score = models.IntegerField(default=0)
    blue_score = models.IntegerField(default=0)
    match_events = models.TextField(max_length=1000)
    teams = models.ManyToManyField(Team, through='Position',
                                   related_name='matches')


class Position(models.Model):
    match = models.ForeignKey(Match)
    color = models.CharField(max_length=5)
    number = models.IntegerField()
    team = models.ForeignKey(Team)

在这种情况下,您将获得更多简化数据访问的选项,例如: 如果team是您的实际团队,并且在代码中某处选择了match单个匹配,那么这是有效的:

team.matches.filter(red_score__gt=F('blue_score')) # all won matches of this team

match.teams.all() # teams involved in this match