如何从模型中使用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屋!