I have a model class:
我有一个模型类:
class Person(db.Model):
first_name = db.StringProperty(required=True)
last_name = db.StringProperty(required=True)
I have an instance of this class in p
, and string s
contains the value 'first_name'
. I would like to do something like:
我在p中有这个类的实例,而字符串s包含值'first_name'。我想做的事情如下:
print p[s]
and
p[s] = new_value
Both of which result in a TypeError
.
两者都会导致TypeError。
Does anybody know how I can achieve what I would like?
有谁知道我怎么能达到我的意愿?
5 个解决方案
#1
7
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.
如果模型类足够智能,它应该识别标准的Python方法。
Try:
getattr(p, s)
setattr(p, s, new_value)
There is also hasattr available.
还有hasattr可用。
#2
3
With much thanks to Jim, the exact solution I was looking for is:
非常感谢Jim,我正在寻找的确切解决方案是:
p.properties()[s].get_value_for_datastore(p)
To all the other respondents, thank you for your help. I also would have expected the Model class to implement the python standard way of doing this, but for whatever reason, it doesn't.
致所有其他受访者,谢谢你的帮助。我也希望Model类能够实现python标准的方法,但无论出于何种原因,它都没有。
#3
1
getattr(p, s)
setattr(p, s, new_value)
#5
-1
p.first_name = "New first name" p.put()
p.first_name =“新名字”p.put()
or p = Person(first_name = "Firsty", last_name = "Lasty" ) p.put()
或者p = Person(first_name =“Firsty”,last_name =“Lasty”)p.put()
#1
7
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.
如果模型类足够智能,它应该识别标准的Python方法。
Try:
getattr(p, s)
setattr(p, s, new_value)
There is also hasattr available.
还有hasattr可用。
#2
3
With much thanks to Jim, the exact solution I was looking for is:
非常感谢Jim,我正在寻找的确切解决方案是:
p.properties()[s].get_value_for_datastore(p)
To all the other respondents, thank you for your help. I also would have expected the Model class to implement the python standard way of doing this, but for whatever reason, it doesn't.
致所有其他受访者,谢谢你的帮助。我也希望Model类能够实现python标准的方法,但无论出于何种原因,它都没有。
#3
1
getattr(p, s)
setattr(p, s, new_value)
#4
#5
-1
p.first_name = "New first name" p.put()
p.first_name =“新名字”p.put()
or p = Person(first_name = "Firsty", last_name = "Lasty" ) p.put()
或者p = Person(first_name =“Firsty”,last_name =“Lasty”)p.put()