How to get foreign key values with getattr from models

落爺英雄遲暮 提交于 2019-12-03 00:15:52

You can do something like follows:

def get_repr(value): 
    if callable(value):
        return '%s' % value()
    return value

def get_field(instance, field):
    field_path = field.split('.')
    attr = instance
    for elem in field_path:
        try:
            attr = getattr(attr, elem)
        except AttributeError:
            return None
    return attr

for field in fields:
    context['project'][field] = get_repr(get_field(project, field))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!