返回变量属性的对象属性值

时间:2013-05-07 03:32:11

标签: python google-app-engine jinja2

我正在尝试设置一个包含对象列表,对象属性名称和对象属性值的调试页面。我试图获取特定对象类型的特定属性的值。我在编码时都不知道对象类型或属性。

以下是我得到的相关章节:

在我的test.py

if self.request.get('objID'):
  qGet = self.request.get
  thisObj = db.get(db.Key(qGet('objID')))

template_values = { 'thisObj' : thisObj }

template = JINJA_ENVIRONMENT.get_template('objProp.html')
self.response.write(template.render(template_values))

和我的objProp.html模板

{% if thisObj %}
  <ul>List of properties
  {% for p in thisObj.properties() %}
    <li>{{ p }} : {{ thisObj.p }}</li>
  {% endfor %}
  </ul>
{% endif %}

然而,由于thisObj中没有属性p,它总是打印出一个空值,实际上我想要打印出p在循环中特定点引用的属性值

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

这是我开始工作的一种方法。我不会接受它,因为我还没有卖掉,因为它是一种“好”的方法。

另请参阅:Google App Engine: how can I programmatically access the properties of my Model class?

这个问题让我大部分都在那里,这就是我正在使用的东西,它似乎运作正常:

{% if thisObj %}
  <ul>List of properties
  {% for p in thisObj.properties() %}
    <li>{{ p }} : {{ thisObj.properties()[p].get_value_for_datastore(thisObj) }}</li>
  {% endfor %}
  </ul>
{% endif %}

似乎p正在以字符串形式解析,thisObj.properties()[p]正在返回object属性,然后我只需要使用.get_value_for_datastore(thisObj)

从该对象中获取值

参考文档:The Property Class

答案 1 :(得分:0)

您不应该使用thisObj.p,因为您没有在thisObj中查找名称。此实例中的.p不是循环中的p,而是尝试引用名为“p”的属性或方法。

你应该使用

getattr(thisObj,p)

相关问题