Limit number of foreign keys

django, django-models

Solution

Normally you need to override the form:

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

If `Round` is inline-edited in the change form page of `Team`, you could limit the `max_num` of `RoundInline`.

Problem

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?

Original source