[英]Django - How to restrict Foreign Key choices to a ManyToMany field in another model
I have 3 models: Championship
, Team
and Match
. 我有3个模型:
Championship
, Team
和Match
。 Championship
and Team
are related with a ManyToManyField
because each team can participate in multiple championships and each championship has many teams. Championship
和Team
与ManyToManyField
相关联,因为每个团队可以参加多个冠军,并且每个冠军都有很多团队。 And each match should be linked to a championship but also to 2 teams that are in the championship. 每场比赛都应与一个冠军联系在一起,但也应与冠军中的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()
I would like to ensure that 'team1' and 'team2' are in 'championship'. 我想确保“ team1”和“ team2”处于“冠军”状态。 And also that 'team1' and 'team2' are different.
而且“ team1”和“ team2”是不同的。
How could I do that ? 我该怎么办?
Maybe i could use something like Django-smart-selects but i would prefer to avoid using a third-party app. 也许我可以使用Django-smart-selects之类的东西,但我宁愿避免使用第三方应用程序。
You can do model validation in the save
method: 您可以在
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.