谷歌应用引擎 - ndb查询只能在python中获取几列

Kri*_*nya 4 python google-app-engine app-engine-ndb google-cloud-datastore

在谷歌应用程序引擎中,是否可以查询数据库只获取某些列?

例如,我有一个模型定义如下:

class userData(ndb.Model):
    id = ndb.StringProperty()
    name = ndb.StringProperty()
    emailAddress = ndb.StringProperty()
Run Code Online (Sandbox Code Playgroud)

我通常查询db如下:

userData.query().filter(ndb.GenericProperty('id') == "requiredId").fetch()
Run Code Online (Sandbox Code Playgroud)

但这给了我包含id,姓名和电子邮件的结果.

现在我想只获取id和name但不是emailAddress.我怎样才能做到这一点?

谢谢!

Jim*_*ane 11

您需要的是投影查询

的exaple:

qry = Article.query()
articles = qry.fetch(20, projection=[Article.author, Article.tags])
for article in articles:
  # code here can use article.author, article.tags
  # but cannot use article.title
Run Code Online (Sandbox Code Playgroud)

你的代码:

class userData(ndb.Model):
    id = ndb.StringProperty()
    name = ndb.StringProperty()
    emailAddress = ndb.StringProperty()

user = userData.query().filter(ndb.GenericProperty('id') ==  "requiredId")\
                       .fetch(projection=[userData.id, userData.name])
Run Code Online (Sandbox Code Playgroud)

虽然我需要引用文档:

投影可能很有用; 如果您只需要两个来自多个大型实体的小属性,则获取更有效,因为它获取和反序列化更少的数据.

使用投影查询时,请考虑以上内容

PS

如果要遵循PEP,还可以在python中对类名使用CapWords约定