繁体   English   中英

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

[英]Django - How to restrict Foreign Key choices to a ManyToMany field in another model

我有3个模型: ChampionshipTeamMatch ChampionshipTeamManyToManyField相关联,因为每个团队可以参加多个冠军,并且每个冠军都有很多团队。 每场比赛都应与一个冠军联系在一起,但也应与冠军中的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之类的东西,但我宁愿避免使用第三方应用程序。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM