2008-09-18 54 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()

相关问题