Use field value in limit_choices_to in Django

一笑奈何 提交于 2019-12-10 09:37:05

问题


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}

回答1:


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


来源:https://stackoverflow.com/questions/28901089/use-field-value-in-limit-choices-to-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!