【问题标题】:google app engine - ndb query to only get a few columns in python谷歌应用引擎 - ndb 查询只能在 python 中获取几列
【发布时间】:2014-09-03 06:09:00
【问题描述】:

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

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

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

我一般查询db如下:

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

但这给了我包含 id、name 和 email 的结果。

现在我只想获得 id 和 name,而不是 emailAddress。我该怎么做?

谢谢!

【问题讨论】:

    标签: python google-app-engine app-engine-ndb google-cloud-datastore


    【解决方案1】:

    你需要的是projection query

    例子:

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

    虽然我需要引用docs:

    投影很有用;如果您每个人只需要两个小属性 从几个大型实体中,获取更有效,因为它得到 并反序列化更少的数据。

    在使用投影查询时考虑以上问题

    附言

    如果你想遵循PEP,也可以在 python 中对类名使用 CapWords 约定

    【讨论】:

    • 感谢@Jimmy Kane 的回答,我也会关注 PEP。
    • 投影效果很好,但如果列例如是一个长的未索引的 TextProperty 或 JsonProperty 它将不起作用。我仍然想知道将这些列包含在子集选择中的最佳方法是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2015-05-15
    • 1970-01-01
    相关资源
    最近更新 更多