AppEngine: Is it possible to write a dynamic property (db.Expando) with the name selected at run time?

If I have an object derived from db.Expando, I can write the Dynamic property by simply assigning a value to the new property, for example. "y" in this example:

class MyEntity(db.Expando):  
  x = db.IntegerProperty()  

my_entity = MyEntity(x=1)  
my_entity.y = 2  

But suppose I have a dynamic property name in a variable ... how can I (1) read and write to it, and (2) check if a dynamic variable exists in an entity instance? eg.

class MyEntity(db.Expando):  
  x = db.IntegerProperty()  

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]  

Thank...

+3
source share
1 answer

Yes, you can. You just need to set the attribute in the entity:

some_name = 'wee'
setattr(my_entity, some_name, 'value')
print getattr(my_entity, some_name)
my_entity.put()

setattr getattr Python, / .

+6

Source: https://habr.com/ru/post/1750279/


All Articles