unique_together on self

时间:2011-12-25 06:19:39

标签: django django-models

我正在使用Django在足球联赛管理网站上工作。其中,我有以下型号:

class PlayerRole(Model):
    player = OneToOneField(Player, primary_key=True)
    team = ForeignKey(Team, null=True)
    role = CharField(max_length=20, choices=PLAYER_ROLES)
    #role can be either "Captain" or "Regular" for a certain team
    class Meta:
        unique_together = ("player", "team")

class Season(Model):
    start_date = DateTimeField(null=True, blank=True)
    end_date = DateTimeField(null=True, blank=True)
    label = CharField(max_length=20)
    team = ManyToManyField(Team, null=True, blank=True)
    player_role = ManyToManyField(PlayerRole, null=True, blank=True)

这个想法是跟踪玩家在某个赛季中扮演的角色。现在我想对season和player_role强制执行unique_together约束,这样在一个赛季中一名球员只能拥有一个角色,但是在多个赛季中,玩家可以拥有多个角色。显然,unique_together ('season', 'player_role')unique_together(self, 'player_role')不起作用(这些只是我的头脑)。

所以我的问题是 - 如何实现所描述的约束?

1 个答案:

答案 0 :(得分:1)

OneToOneField强制执行player上的唯一身份,因此unique_together是多余的。要使模型有效,您应将其player更改为ForeignKey

以下型号可能会更好地满足您的需求:

class Season(Model):
    start_date = DateTimeField(null=True, blank=True)
    end_date = DateTimeField(null=True, blank=True)
    label = CharField(max_length=20)

class PlayerRole(Model):
    season = ForeignKey(Season)
    player = ForeignKey(Player)
    team = ForeignKey(Team)
    role = CharField(max_length=20, choices=PLAYER_ROLES)
    #role can be either "Captain" or "Regular" for a certain team
    class Meta:
        unique_together = ("season", "player")
        # OR, TO ALLOW PLAYERS MOVING BETWEEN TEAM IN SEASON:
        # unique_together = ("season", "player", "team")