Reputation:
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
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
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