2008-09-18 52 views
8

我有一個模型類:Google App Engine:我如何以編程方式訪問我的Model類的屬性?

class Person(db.Model): 
    first_name = db.StringProperty(required=True) 
    last_name = db.StringProperty(required=True) 

我有這個類的一個實例在p和字符串s包含值'first_name'。我想這樣做:

print p[s] 

p[s] = new_value 

這兩者導致TypeError

有誰知道我可以如何實現我想要的?

+0

`dir(p)`顯示什麼? – 2008-09-18 11:53:22

回答

1
getattr(p, s) 
setattr(p, s, new_value) 
+0

嗨吉姆,謝謝你的回覆。上面的代碼導致了一個AttributeError。 – 2008-09-18 11:58:27

1

嘗試:

p.model_properties()[s].get_value_for_datastore(p) 

the documentation

+0

即使工作? model_properties是一個類方法,而不是一個實例方法。 – 2008-09-18 12:17:48

+0

謝謝你,你把我放在正確的道路上。確切的答案是p.properties()[s] .get_value_for_datastore(p) – 2008-09-18 22:44:25

7

如果模型類足夠智能,它應該認識到Python的標準方法。

嘗試:

getattr(p, s) 
setattr(p, s, new_value) 

還有hasattr可用。

+0

我已經使用GAE和getattr和setattr工作正常。 – 2008-09-18 12:23:34

3

由於大部分歸功於吉姆,我一直在尋找確切的解決方案是:

p.properties()[s].get_value_for_datastore(p) 

所有其他受訪者,感謝你的幫助。我也希望Model類能夠實現python標準的這種做法,但無論出於何種原因,它都沒有。

-1

p.first_name = 「新名字」 p.put()

或P =人(如first_name = 「Firsty」, 姓氏= 「Lasty」) p.put()

相關問題