user2540748
user2540748

Reputation:

Limit choices on model to self reference

I have a model that has a recursive reference to itself.

class Section(models.Model):
    report = models.ForeignKey(Report)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children', limit_choices_to= ... )

Is there a way I can limit the parent choices to sections that belong to the same report?

Upvotes: 3

Views: 544

Answers (2)

Brandon Taylor
Brandon Taylor

Reputation: 34583

You should be able to do this in a ModelForm, but I have NOT tested this code.

class SectionForm(forms.ModelForm):
    class Meta:
        model = Section

    def __init__(self, *args, **kwargs):
        super(SectionForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['parent'].queryset = self._meta.model.objects.filter(
                report=self.instance.report)

Upvotes: 1

jsmedmar
jsmedmar

Reputation: 1125

What about using a custom validator?

Check if the new pk is part of the subset you require, otherwise raise a ValidationError.

Upvotes: 0

Related Questions