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?
A table can have multiple foreign keys based on the requirement.
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.
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.
There is no problem having a table that consists of foreign keys only.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With