【问题标题】:How to programmatically compose ndb.AND to query a repeated property?如何以编程方式编写 ndb.AND 来查询重复的属性?
【发布时间】:2019-12-14 13:35:39
【问题描述】:

我有一个 Google App 引擎 NDB 的实体,它有一个重复的 KeyProperty,我想在元素列表上使用“包含 AND”进行查询。

我指的是这里列出的“解决方案2”:How to query with a list object on repeated string property in ndb,问题是我不知道查询列表有多少元素。

这是我的模型:

class Record(ndb.Expando):
    name = ndb.StringProperty(required=True)
    ref = ndb.KeyProperty(Client, repeated=True)

以及我的查询尝试:

q = Record.query()
for client in getlist('ref[]'):
            q.filter(Record.ref == ndb.Key(urlsafe=client))

q.filter(Record.ref == [ndb.Key(urlsafe=elem) for elem in getlist('ref[]')])

我认为在重复属性上实现包含和查询的最佳方法是使用ndb.AND 运算符,如https://cloud.google.com/appengine/docs/standard/python/ndb/queries#nest_and_or 和上面提到的 SO 响应中,但我需要用未知数字“组合”它元素...ndb.AND(kind.prop==elem_1, kind.prop==elem_2, ...kind.prop==elem_N).

【问题讨论】:

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


    【解决方案1】:

    我不太确定ndb.AND 是否会接受以编程方式生成的可用于过滤的字符串。

    因此,您可以采用的另一种方法是使用 IN 过滤器。在documentation 中有关于如何过滤重复属性的信息以及IN 的用法示例。

    我将遵循的过程是:

    # generate properties to filter
    #property array will look like:
    #[poperty1, property2, property3, ....., propertyN]
    properties = [property for property in properties]
    
    # filter using the previous generated properties
    q = Records.query(Records.ref.IN(properties))
    
    # then manually filter the results
    for result in q:
    # apply custom filters
        if result.ref == 'property1' and result.ref == 'property2':
            #dosomething
    

    通过这种方式,您可以实现类似的功能,因为您将首先拥有包含至少一个来自IN 过滤器的属性的实体,然后您可以手动处理它们并实现 AND 过滤器。

    【讨论】:

    • 如果 - 如问题所述 - 我不知道属性数组中有多少元素?
    • 我猜你说你不知道你在代码中创建了多少元素?可以通过编程方式创建属性数组,因此即使您不知道 N 的确切值,代码也会创建 N 个属性。我正在编辑答案以使其更清晰。
    【解决方案2】:

    根据一些更深入的谷歌搜索,也许我在 NDB 中的一对多方法是错误的。

    现在我正在尝试将引用属性保留在被引用的实体中......如:

    class Client(ndb.Model):
      prop = ndb.StringProperty()
      ref = ndb.KeyProperty(Record, repeated=True)
    
    class Record(ndb.Model):
      prop = ndb.StringProperty()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2021-01-30
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多