代码之家  ›  专栏  ›  技术社区  ›  kafuchau

Django:获取外键类型

  •  2
  • kafuchau  · 技术社区  · 16 年前

    是否有方法获取与我的密钥相关的型号的外键类型?目前,我正在尝试以下方法:

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


    任何帮助都将不胜感激。

    2 回复  |  直到 16 年前
        1
  •  4
  •   kafuchau    16 年前

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

        getattr(type(self.instance), field).field.rel.to
    
        2
  •  2
  •   user2085368    6 年前

    为Django 2.2更新,其中 field.rel.to

     getattr(type(self.instance), field).field.related_model
    
        3
  •  1
  •   cethegeek    16 年前

    也许你应该调查一下 generic relations

    推荐文章