exfizik
exfizik

Reputation: 5721

unique_together on self

I'm working on a soccer league management website using Django. Among others, I have the following models:

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)

The idea is to keep track of what role a player had during a certain season. Now I would like to enforce a unique_together kind of constraint on season and player_role so that during one season a player could only have one role, but across multiple seasons players can have multiple roles. Apparently, unique_together ('season', 'player_role') and unique_together(self, 'player_role') don't work (those were just off the top of my head).

So my question is - How does one implement the described constraint?

Upvotes: 1

Views: 306

Answers (1)

Udi
Udi

Reputation: 30534

The OneToOneField enforces a unique on player, therefore the unique_together is redundant. To make your model work you should change it player to a ForeignKey.

The following models would probably be a little better for your needs:

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") 

Upvotes: 1

Related Questions