I have a number of different models (ModelA, ModelB) which include a KeyProperty referring to entities of a common model (ModelC). I have a method which needs to do some processing using the entity referred to by multiple instances of ModelA and ModelB, but the KeyProperty for each model is named differently, and should be as they serve fundamentally different roles in ModelA and ModelB. The processing I require using the KeyProperty referencing ModelC is identical lists of entities for ModelA and ModelB, so I should be able to define a common method which can be called on both, but how do I tell this method which property to use?
Can I use the Model’s property attribute to retrieve the value of that property from an entity?
I’ve looked through the App Engine docs on NDB extensively and I can’t work out how to do this. Either its extremely trivial, or I missed something in the documentation, but I just can’t work this out.
I’ll provide a trivial example below:
Models:
class ModelA(ndb.Model):
name = ndb.StringProperty()
last_model_c = ndb.KeyProperty(kind='ModelC')
...
class ModelB(ndb.Model):
sku = ndb.StringProperty()
first_use_model_c = ndb.KeyProperty(kind='ModelC')
...
class ModelC(ndb.Model):
...
Call to Processing:
...
q = ModelA.query()
...
self.model_c_scan(q.fetch(), ModelA.last_model_c)
...
q = ModelB.query()
...
self.model_c_scan(q.fetch(), ModelB.first_use_model_c)
Processing:
...
def model_c_scan(entity_list, property)
...
for entity in entity_list:
model_c_key = <get the entity's value for the property>
model_c = model_c_key.get()
...
The solution I found was to specify the name of the Property using a string, and simply use python’s
getattr().Pure python method
getattr()which also compatible ndb Models works like below: