Django - 如何将外键选择限制为另一个模型中的ManyToMany字段

时间:2017-02-24 21:08:42

标签: python django django-models foreign-keys

我有3个模型:ChampionshipTeamMatchChampionshipTeamManyToManyField相关,因为每个团队都可以参加多个锦标赛,每个锦标赛都有很多团队。 每场比赛都应该与冠军相关联,但也要与2支参加锦标赛的球队联系起来。

class Championship(models.Model):
    name = models.CharField(max_length=100)
    teams = models.ManyToManyField(Team)

class Team(models.Model):
    name = models.CharField(max_length=100)

class Match(models.Model):
    championship = models.ForeignKey(Championship)
    team1 = models.ForeignKey(Team)
    team2 = models.ForeignKey(Team)
    score1 = models.PositiveIntegerField()
    score2 = models.PositiveIntegerField()

我想确保'team1'和'team2'处于'冠军'状态。而且'team1'和'team2'也不同。

我怎么能这样做?

也许我可以使用Django-smart-selects这样的内容,但我宁愿避免使用第三方应用。

1 个答案:

答案 0 :(得分:2)

您可以使用save方法进行模型验证:

from django.core.exceptions import ValidationError


class Match(models.Model):
    championship = models.ForeignKey(Championship)

    team1 = models.ForeignKey(Team)
    team2 = models.ForeignKey(Team)

    score1 = models.PositiveIntegerField()
    score2 = models.PositiveIntegerField()

    def save(self, *args, **kwargs):
        if self.team1 == self.team2:
            raise ValidationError('The two teams in a match must be distinct')

        all_teams = self.championship.teams.all()

        if self.team1 not in all_teams or self.team2 not in all_teams:
            raise ValidationError('Both teams must be in the championship')

        return super(Match, self).save(*args, **kwargs)
相关问题