如何在Django ModelForm中过滤ManyToManyField选项?

时间:2012-04-18 09:33:58

标签: python django django-forms django-orm

我想在我的ModelForm中过滤ManyToManyField选项:

class MyForm(forms.ModelForm):
    class Meta:
        model = Entity
        fields = ['parent_entities']

    def __init__(self, *args, **kwargs):
        self.root_entity = kwargs.pop('root_entity')
        self.Meta.fields['parent_entities'].queryset = Entity.objects.filter(root_entity=self.root_entity)
        super(MyForm, self).__init__(*args, **kwargs)

我尝试了很多不同的代码,但我还没有看到任何代码。

我想我的问题是我无法获得这个'parent_entities'字段。 使用此代码,我有错误:

list indices must be integers, not str

1 个答案:

答案 0 :(得分:6)

def __init__(self, *args, **kwargs):
   # First pop your kwargs that may bother the parent __init__ method
   self.root_entity = kwargs.pop('root_entity')
   # Then, let the ModelForm initialize:
   super(MyForm, self).__init__(*args, **kwargs)
   # Finally, access the fields dict that was created by the super().__init__ call
   self.fields['parent_entities'].queryset = Entity.objects.filter(root_entity=self.root_entity)