如何在NDB中的重复字符串属性上使用列表对象进行查询 [英] How to query with a list object on repeated string property in ndb

查看:64
本文介绍了如何在NDB中的重复字符串属性上使用列表对象进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Google App Engine时,我使用ndb来管理数据. 我有一个使用重复的字符串属性保存字符串值列表的实体. 如何使用等于属性值的列表对象进行查询?

With google app engine, I use ndb to manange my data. I have a entity that use a repeated string property to save a list of string values. How can I query with a list object that is equal to the property value?

我的意思是,实体是

class Question(ndb.Model):
    question = ndb.StringProperty(required=True)
    choices = ndb.StringProperty(repeated=True)

我想这样查询:

question = "The question"
choices = ["Choice1", "Choice2", ..., "Choice6"]
Question.query(Question.question==question, Question.choices==choices)

推荐答案

当您具有重复属性时,将无法执行查询以完全等同于该列表的查询.

When you have a repeated property, there is no way to perform a query searching for exact equality of that list.

例如,一个带有以下内容的Question实体:

For example, a Question entity with:

question = "A question"
choices = ["A", "B", "C"]

将匹配以下查询的全部

Question.query(Question.choices=="A")
Question.query(Question.choices=="B")
Question.query(Question.choices=="C")


解决方案1:计算属性


Solution 1: Computed Property

如果您要编写一个查询,其中整个列表相等,则可以使用计算属性,该属性是重复属性的字符串化版本:

If you want to write a query where the entire list is equal, you could use a computed property that is a stringified version of your repeated property:

class Question(ndb.Model):
    question = ndb.StringProperty(required=True)
    choices = ndb.StringProperty(repeated=True)
    choices_list = ndb.ComputedProperty(lambda self: return ",".join(self.choices))

然后使用choices_list进行查询:

choices = [...]
Question.query(Question.choices_list==",".join(choices))

当然,只有choices完全匹配(包括顺序)时,此匹配项才会出现.

Of course, this will only match if the choices match exactly (including order).

解决方案2:使用AND

Solution 2: Using AND

您还可以使用AND查询:

You could also use an AND query:

choices = [...]
Questions.query(
                ndb.AND(Question.choices==choices[0],
                ....,
                Question.choices==choices[n])) # Do this in a programmatic way

此解决方案的好处在于,列表的顺序无关紧要,但是可能会导致误报,因为对["A","B"]的查询将匹配具有选择项["A"的实体, "B","C"].

This solution has the upside that the ordering of your list does not matter, however it may result in false positives, as a query for ["A", "B"] will match an entity with choices ["A", "B", "C"].

这篇关于如何在NDB中的重复字符串属性上使用列表对象进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆