2

有没有办法获取与我的键相关的模型的外键类型?目前,我正在尝试类似:

def __init__(self, *args, **kwargs):
        super(JobOrderSupplementForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            if type(self.fields[field]) == TypedChoiceField:
                fieldOption = <Whatever type key points to>.get(id=self.__dict__['initial'][field])
                if not fieldOption.isActive:
                    ...Do something to the choices...


我正在尝试以编程方式设置将在我的表单中显示的可用选项。到目前为止,我只能弄清楚下面的这个片段让我与外键对象有某种关系......

self.fields[field].__dict__['coerce']
>>> <bound method ForeignKey.to_python of <django.db.models.fields.related.ForeignKey object at 0x01609EF0>>


任何帮助将不胜感激。

4

3 回答 3

4

想通了...这是一个非常复杂且乏味的 dir 和 type 过程,但是,这一行将为我提供与外键相关的 Model 类型:

    getattr(type(self.instance), field).field.rel.to
于 2009-12-18T20:13:35.580 回答
2

为 Django 2.2 更新,其中field.rel.to对象路径不再出现解析,

 getattr(type(self.instance), field).field.related_model
于 2019-07-05T19:40:39.323 回答
1

也许您应该研究泛型关系

于 2009-12-18T20:16:50.210 回答