【问题标题】:Django: Getting the foreign key typeDjango:获取外键类型
【发布时间】:2010-12-28 03:48:42
【问题描述】:

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

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...


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

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


任何帮助将不胜感激。

【问题讨论】:

    标签: django django-models foreign-keys foreign-key-relationship


    【解决方案1】:

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

     getattr(type(self.instance), field).field.related_model
    

    【讨论】:

      【解决方案2】:

      也许你应该看看generic relations

      【讨论】:

        【解决方案3】:

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

            getattr(type(self.instance), field).field.rel.to
        

        【讨论】:

          猜你喜欢
          • 2011-11-29
          • 2020-06-30
          • 2012-05-07
          • 2016-10-24
          • 1970-01-01
          • 2014-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多