Swordsfrog
Swordsfrog

Reputation: 119

How to query with a list object on repeated string property in 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?

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)

Upvotes: 1

Views: 1305

Answers (1)

Patrick Costello
Patrick Costello

Reputation: 3626

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

Upvotes: 2

Related Questions