2017-02-24 124 views
0

我有3個型號:Championship,TeamMatchChampionshipTeamManyToManyField相關,因爲每個團隊都可以參加多個錦標賽,而且每個錦標賽都有很多團隊。 每一場比賽都應該與錦標賽有關,但也應該與兩支冠軍隊相關。Django - 如何限制外鍵選擇到另一個模型中的ManyToMany字段

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的東西,但我寧願避免使用第三方應用程序。

回答

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) 
+0

謝謝,這正是我一直在尋找。 – Serphone

相關問題