AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime?
If I have an entity derived from db.Expando I can write Dynamic property by just assigning a value to a new property, e.g. "y" in this example:
class MyEntity(db.Expando):
x = db.IntegerProperty()
my_entity = MyEntity(x=1)
my_entity.y = 2
But suppose I have the name of the dynamic property in a variable... how can I (1) read and write to it, and (2) check if the Dynamic variable exists in the entity's instance? e.g.
class MyEntity(db.Expando):
x = db.IntegerProperty() 开发者_JS百科
my_entity = MyEntity(x=1)
# choose a var name:
var_name = "z"
# assign a value to the Dynamic variable whose name is in var_name:
my_entity.property_by_name[var_name] = 2
# also, check if such a property esists
if my_entity.property_exists(var_name):
# read the value of the Dynamic property whose name is in var_name
print my_entity.property_by_name[var_name]
Thanks...
Yes, you can. You simply have to set the attribute on the entity:
some_name = 'wee'
setattr(my_entity, some_name, 'value')
print getattr(my_entity, some_name)
my_entity.put()
setattr
and getattr
are built-in functions of Python used to set/get attributes with arbitrary names on an object.
精彩评论