Search code examples
djangodjango-modelsdjango-mptt

Use field value in limit_choices_to in Django


I have two models Project and Group. My groups belong to a specific project. My groups have the fields project = ForeignKey(Project) and parent = ForeignKey('self').

Can I use limit_choices_to to make sure the options in foreign key parent only consist of groups inside the same project?

I'm thinking of something like

def limit_choices_to(self):
    return {'project': self.project}

Solution

  • This is impossible to do at the model level but you can change the queryset for this field in the form's constructor.

    class GroupForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(GroupForm, self).__init__(*args, **kwargs)
            if self.instance.project:
                self.fields['parent'].queryset = Group.objects.filter(
                                                    project=self.instance.project)
    

    UPDATE: To do it in the admin you have to set the form attribute of the ModelAdmin:

    class GroupAdmin(admin.ModelAdmin):
        form = GroupForm