【问题标题】:GAE ndb query excluding entityGAE ndb 查询不包括实体
【发布时间】:2012-08-09 03:19:22
【问题描述】:

我想编写一个 ndb 查询,从结果集中排除由其 id 标识的特定实体。

我尝试了以下方法:

result = Entity.query(Entity.key.id() != 'entity-id', *some other condition*).fetch()

Entity.key.id() != 'entity-id' 位会引发错误。什么是正确的语法?

【问题讨论】:

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


    【解决方案1】:

    我不知道是否可以在键上查询排除,您有一个简单的解决方法可以从最终结果中删除结果。

    但如果它有效,语法应该是这样的:

    result = Entity.query(Entity.key != ndb.Key(Entity, id), *some other condition*).fetch()
    

    【讨论】:

    • 这对我不起作用。我相信您必须使用 from_path() Key 方法从种类和 ID 构建 Key 对象。此外,要引用实体的密钥,您需要使用 __key__ 语法,请参阅我的答案。
    • @HorseloverFat from_path() 和 Key() 基本相同。
    • 我没有发现它们在 db API 中是相同的。如果我将答案中的.Key.from_path 替换为.Key,则会出现错误。
    【解决方案2】:

    可以使用 db API 根据其 id 排除特定实体(我假设 ndb API 有一些小的改动)。以下语法适用于我使用 db API。它使用排除 id_to_retrieve 变量中的 id 的结果构建查询:

    id_to_retrieve = 123456
    query = Entity.all() 
    query.filter('__key__ !=',  db.Key.from_path('Entity', id_to_retrieve))
    query.fetch(None)
    

    【讨论】:

    • 您使用的是 db API 而不是 ndb API。
    • 好点。我没有注意到这是一个 ndb 问题。我会更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2014-06-11
    • 2014-03-06
    相关资源
    最近更新 更多