Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of foreign keys

Let's take this example:

class Team (models.Model):
    name = models.CharField('Name', max_length=30)

class Round (models.Model):
    round_number = models.IntegerField('Round', editable=False) #Auto-incrementing per Team
    team = models.ForeignKey(Team)

There is a limit of 3 rounds. How can I raise an error inside the Admin and generally prevent a team from having more than 3 Rounds?

like image 703
Azsgy Avatar asked Jul 05 '14 12:07

Azsgy


People also ask

Can a table have 3 foreign keys?

A table can have multiple foreign keys based on the requirement.

How many primary and foreign keys can a table have?

Helps us to identify data in a database table. Helps to identify the data in another table using the connection with the foreign key. A table can have only one Primary Key. A table can have any number of Foreign Keys.

Why foreign key is not recommended?

There's one good reason not to use them: If you don't understand their role or how to use them. In the wrong situations, foreign key constraints can lead to waterfall replication of accidents. If somebody removes the wrong record, undoing it can become a mammoth task.

Can table only have one foreign key?

There is no problem having a table that consists of foreign keys only.


1 Answers

I liked the way using the validator:

def restrict_amount(value):
    if Round.objects.filter(team_id=value).count() >= 3:
        raise ValidationError('Team already has maximal amount of rounds (3)')


class Team (models.Model):
    name = models.CharField('Name', max_length=30)


class Round (models.Model):
    round_number = models.IntegerField('Round', editable=False) #Auto-incrementing per Team
    team = models.ForeignKey(Team, validators=(restrict_amount, ))

Using validator will make Django handle it properly, for example, display an error in the admin panel.

like image 130
Ignis Avatar answered Nov 15 '22 11:11

Ignis