如何使用 getattr 从模型中获取外键值 [英] How to get foreign key values with getattr from models
问题描述
我有一个模型 Project
并且我正在使用以下指令获取它的属性
I have a model Project
and i am getting the attributes of that with the following instr
attr = getattr(project, 'id', None)
project
是实例,id
是字段,None
是默认返回类型.
project
is the instance, id
is the field and None
is the default return type.
我的问题是:如果我想用这个获取外键怎么办?
My question is: what if I want to get the Foreign Key keys with this?
project.customer.name
满足以上条件如何获取客户名称?
project.customer.name
How to get customer name with the above condition?
if callable(attr):
context[node][field] = '%s' % attr()
当前代码
context = {'project': {}}
fields = ('id', 'name', 'category', 'created_by', customer)
for field in fields:
attr = getattr(project, field, None)
if callable(attr):
context['project'][field] = '%s' % attr()
else:
context['project'][field] = attr
我需要在这里调整客户对象.我可以在我的字段中提供诸如 customer__name
或 customer.name
之类的东西,并且它会填充客户的姓名,但我不确定.
i need to adjust customer object here. that i can give something like customer__name
or customer.name
in my fields and it get populated with the name of the customer, but i am not sure.
推荐答案
您可以执行以下操作:
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))
这篇关于如何使用 getattr 从模型中获取外键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!