Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Limiting the number of relationships in a OnetoMany relationship

Hi i was looking to limit a ForeignKey relationship to as specific number.
Lets say there can only be 12 people on a basketball team.

class Team(models.Model):
 teamName = models.CharField(max_length = 20)
 teamColors = models.CharField(max_length = 20)
 ... <and so forth>

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

** is there an option to would limit up to 12 players per team here?

with any additional creating a python error?

like image 666
thespineer Avatar asked Jan 07 '11 00:01

thespineer


People also ask

How does Django handle many to many relationship?

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it.

What is Onetoone field in Django?

One-to-one fields:This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle.


1 Answers

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.

like image 90
Crast Avatar answered Sep 21 '22 06:09

Crast