如何从django ForeignKey字段解析对象

时间:2014-05-18 00:29:57

标签: django

我尝试以通用方式遍历django对象 -

我无法得到相关的对象:

# field_names has the names of some fields of object

for field_name in field_names:
    field = object._meta.get_field_by_name(field_name)

    if isinstance(field[0], ForeignKey):
        related = getattr(object, field[0].get_attname())

相关然后保存主键值。

但我如何访问该对象?我错过了什么?

2 个答案:

答案 0 :(得分:2)

您可以从rel获取基础相关对象:

field[0].rel.to

您可以使用get_field()

稍微简化代码
for field_name in field_names:
    field = object._meta.get_field(field_name)

    if isinstance(field, ForeignKey):
        related = field.rel.to

答案 1 :(得分:1)

找到解决方案:

field = object._meta.get_field_by_name(field_name)
if isinstance(field[0], ForeignKey):
    fkey = {}
    fkey['name'] = field[0].rel.get_related_field().name
    fkey['value'] =  getattr(object, field[0].get_attname())

    related = field[0].rel.to._default_manager.get(**{fkey['name']: fkey['value']})