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

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

问题描述

通过谷歌应用引擎,我使用 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天全站免登陆