当我的唯一输入是ndb.Query时,如何获取ndb.Model? [英] How can I get the ndb.Model when my only input is an ndb.Query?

查看:55
本文介绍了当我的唯一输入是ndb.Query时,如何获取ndb.Model?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有 ndb.Model 如下所示:

  class Foo(ndb.Model):
bar = ndb.StringProperty()

我的问题是,如果我唯一的输入是 Foo.query()我怎样才能得到模型作为这个查询所属的对象?

  def query_to_model(查询):
#一些魔法
返回模型






Foo.query()。kind 返回模型的名字作为一个字符串,但我没有设法找到一个方法来获取它作为一个对象。



以下工作使用 eval ,但只有当模型在同一个文件中定义时:

  def query_to_model(query):
return eval(query.kind)

我想要比这更普遍的东西。

解决方案

使用此模型定义导入代码后,列表 ndb.Mo del._kind_map 应该包含它。这是魔术:

$ p $ def query_to_model(query):
return ndb.Model._kind_map [query.name]


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.

解决方案

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]

这篇关于当我的唯一输入是ndb.Query时,如何获取ndb.Model?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆