2013-05-07 117 views
0

我試圖用對象,對象屬性名稱和對象屬性值列表設置一個調試頁面。我正在嘗試獲取特定對象類型的特定屬性的值。當我編碼時,對象類型或屬性都不知道。返回變量屬性的對象屬性值

下面是相關的部分我有這樣的:

在我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的值

任何幫助將非常感謝!

回答

0

您不應該使用thisObj.p,因爲您不在thisObj中查找名稱。這個實例中的.p不是來自循環的p,而是試圖引用稱爲「p」的屬性或方法。

您應該使用

getattr(thisObj,p)

+0

我收到getattr()未定義的指示。有沒有辦法在Jinja模板中啓用這個功能? – 2013-05-07 03:53:05

+0

另一個答案是更好的,並工作。我不使用jinja,所以我不知道爲什麼不能訪問getattr – 2013-05-07 05:10:48

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

+0

您可以使用'thisObj.properties()。values()'來避免[p]步驟,然後使用'p.get_value_for_datastore( thisObj)' – 2013-05-07 05:12:03