将ForeignKey字段的选择限制为模型中的实例变量

时间:2019-01-23 13:59:36

标签: django django-models django-forms

我为与比赛相关的应用程序创建了一个Match模型(Team是另一个模型):

class Match(models.Model):
    home_team = models.ForeignKey(Team, related_name="home_team", on_delete=models.CASCADE)
    away_team = models.ForeignKey(Team, related_name="away_team", on_delete=models.CASCADE)
    winning_team = models.ForeignKey(Team, related_name="winning_team", on_delete=models.CASCADE)

我的问题是,是否可以将winning_team字段的选择限制为home_team或away_team?即,如果我创建一个表格来记录获胜的球队,该如何将选择列表中的选择限制为home_team和away_team?

1 个答案:

答案 0 :(得分:0)

最好让winning_team成为“ home_team”和“ away_team”之间的简单选择;如果需要,您可以添加一个属性,以根据该字段的值获得实际的获胜团队。例如:

WINNERS = (
  ('H', 'Home team'),
  ('A', 'Away team'),
)
class Match(models.Model):
    ...
    winners = models.CharField(max_length=1, choices=WINNERS)

    @property
    def winning_team(self):
        return self.home_team if self.winners == 'H' else self.away_team