【问题标题】:Return object property value for variable property返回变量属性的对象属性值
【发布时间】:2013-05-07 03:32:11
【问题描述】:

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

以下是我为之准备的相关部分:

在我的 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 所指的任何属性的值

任何帮助将不胜感激!

【问题讨论】:

    标签: python google-app-engine jinja2


    【解决方案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] 正在返回对象属性,然后我只需要使用 .get_value_for_datastore(thisObj) 从该对象中获取值

    从此处的文档中引用:The Property Class

    【讨论】:

    • 您可以通过使用thisObj.properties().values() 避免[p] 步骤,然后使用p.get_value_for_datastore(thisObj)
    【解决方案2】:

    您不应该使用thisObj.p,因为您没有在thisObj 中查找名称。在这种情况下,.p 不是循环中的 p,而是试图引用名为“p”的属性或方法。

    你应该使用

    getattr(thisObj,p)

    【讨论】:

    • 我得到一个指示 getattr() 未定义。有没有办法在 Jinja 模板中启用此功能?
    • 另一个答案更好,并且有效。我不使用 jinja,所以我不知道为什么无法访问 getattr
    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多