【问题标题】:Django - How to restrict Foreign Key choices to a ManyToMany field in another modelDjango - 如何将外键选择限制为另一个模型中的 ManyToMany 字段
【发布时间】:2017-02-24 21:08:42
【问题描述】:

我有 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' 处于 'championship' 中。而且'team1'和'team2'是不同的。

我该怎么做?

也许我可以使用 Django-smart-selects 之类的东西,但我宁愿避免使用第三方应用。

【问题讨论】:

    标签: python django django-models foreign-keys


    【解决方案1】:

    您可以在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)
    

    【讨论】:

    • 谢谢,这正是我想要的。
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2015-05-29
    • 2011-05-06
    • 2010-10-18
    • 1970-01-01
    • 2019-09-04
    • 2016-08-01
    • 2010-10-22
    相关资源
    最近更新 更多