How to query with a list object on repeated string property in ndb

久未见 提交于 2019-12-11 08:59:08

问题


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?

What I meant is, the entity is

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

and I want to query like this:

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

回答1:


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

For example, a Question entity with:

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

Will match all of the following query

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

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

Then query using the choices_list:

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

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


Solution 2: Using 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

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"].



来源:https://stackoverflow.com/questions/23937355/how-to-query-with-a-list-object-on-repeated-string-property-in-ndb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!