[Solved]-Django: Limiting the number of relationships in a OnetoMany relationship

9👍

There isn’t a direct way to limit the number of players in a team on the ForeignKey definition. However, this can be done with a little bit of working with your model.

One option would be to make a method on Team, something like:

def add_player(self, player):
    if self.player_set.count() >= 12:
         raise Exception("Too many players on this team")

    self.player_set.add(player)

Then you would want to always add players through this method.

👤Crast

4👍

I think another option would be to override the save method on the Player model like this:

class Player(models.Models):
    team = models.ForeignKey(Team, **)
    name = models.CharField(max_length = 20)
    heightInches = models.IntegerField()
    ... <and so forth>

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if self.player_set.count() < 12:
            super(Player, self).save()
        else:
            raise Exception(f'{self.team.teamName} has already 12 players. No more are allowed.')
👤Hernan

Leave a comment