Google App Engine - 使用ndb查询仅获取部分列在Python中

4 投票
1 回答
3325 浏览
提问于 2025-04-18 13:05

在谷歌应用引擎中,能否查询数据库只获取某些列的数据?

比如,我定义了一个模型,内容如下:

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

我通常是这样查询数据库的:

userData.query().filter(ndb.GenericProperty('id') == "requiredId").fetch()

但是这样查询出来的结果包含了id、name和email。

现在我只想获取id和name,而不想要emailAddress。我该怎么做呢?

谢谢!

1 个回答

12

你需要的东西叫做投影查询

举个例子:

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

你的代码:

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])

不过我需要引用一下文档中的内容:

投影查询很有用;如果你只需要从几个大数据中获取两个小属性,这样的查询会更高效,因为它获取和解码的数据更少。

在使用投影查询时,记得考虑以上内容

附言:

如果你想遵循PEP,在Python中为类命名时也要使用大写字母开头的风格。

撰写回答