问题
Let's say there is ndb.Model that looks like this:
class Foo(ndb.Model):
bar = ndb.StringProperty()
My question is, if my only input is the Foo.query() how can I get the model as an object that this query belongs to?
def query_to_model(query):
# some magic
return model
The Foo.query().kind return the model's name as a string, but I didn't manage to find a way to get it as an object.
The following works using eval, but only when the model is defined in the same file:
def query_to_model(query):
return eval(query.kind)
I want something more general than that.
回答1:
After you have imported code with this model definition, the list ndb.Model._kind_map should contain it. Here is the magic:
def query_to_model(query):
return ndb.Model._kind_map[query.name]
回答2:
I use this code to find the model class if you have the kind name:
model_module = KIND_MODULES(kind_name)
mod = __import__(model_module, globals(), locals(), [kind_name], -1)
model_class = getattr(mod, kind_name)
The KIND Modules dict holds the modules to import the models from:
KIND_MODULES = { 'Users' : 'models', 'Comments' : 'models', 'Cities' : 'examples.models' }
来源:https://stackoverflow.com/questions/14651975/how-can-i-get-the-ndb-model-when-my-only-input-is-an-ndb-query