让我们以这个例子为例:
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)
有3轮的限制。我如何在管理员内部提出错误并通常阻止团队超过 3 轮?
最佳答案
我喜欢使用验证器的方式:
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, ))
使用验证器将使 Django 正确处理它,例如,在管理面板中显示错误。
关于django - 限制外键数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24586223/