有没有办法获取我的 key 相关模型的外键类型?目前,我正在尝试类似的事情:
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>>
任何帮助将不胜感激。
最佳答案
弄清楚了......这是一个非常复杂和乏味的目录和类型过程,但是,这一行将让我获得与外键相关的模型类型:
getattr(type(self.instance), field).field.rel.to
关于Django:获取外键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1930140/