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.
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.')
- Call method once to set multiple fields in Django Rest Framework serializer
- Pycharm error: Improperly configured
- After login the `rest-auth`, how to return more information?
- How to configure Apache to run ASGI in Django Channels? Is Apache even required?
- Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?
Source:stackexchange.com