限制外键数量

Azs*_*sgy 5 django django-models

让我们以这个例子为例:

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)
Run Code Online (Sandbox Code Playgroud)

有3轮的限制。我如何在管理员内部提出错误并通常阻止团队超过 3 轮?

小智 13

我喜欢使用验证器的方式:

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, ))
Run Code Online (Sandbox Code Playgroud)

使用验证器将使 Django 正确处理它,例如,在管理面板中显示错误。


okm*_*okm 6

通常你需要覆盖表单:

class RoundAdminForm(forms.ModelForm):
    def clean_team(self):
        team = self.cleaned_data['team']
        if team.round_set.exclude(pk=self.instance.pk).count() == 3:
            raise ValidationError('Max three rounds allowed!')
        return team

class RoundAdmin(admin.ModelAdmin):
    form = RoundAdminForm
Run Code Online (Sandbox Code Playgroud)

如果Round在变化形式页面内嵌编辑Team,你可以限制max_numRoundInline