Python 如何过滤Django模型表单中的许多字段选择?

Python 如何过滤Django模型表单中的许多字段选择?,python,django,django-forms,django-orm,Python,Django,Django Forms,Django Orm,我想筛选模型表单中的许多字段选项: 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['pare

我想筛选模型表单中的许多字段选项:

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)
我尝试了很多我见过的不同的代码,但都没有成功

我想我的问题是我不能得到这个“父实体”字段。 使用此代码,我有一个错误:

list indices must be integers, not str

我以前已经试过了,但是我有一条错误消息:AttributeError'MyForm'对象没有属性'fields',对吧,也许你应该在访问MyForm.fields之前调用父init。如果我这样做,我会出现以下错误(这是有意义的):TypeError uu init uu_;()得到一个意外的关键字参数'root\u entity'。(事实上,我没有看到你改变了初始答案中的行顺序)对,然后在调用init之前弹出kwargs。。。答案更新是的,我的错!谢谢你的回答!
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)