Search code examples
pythongoogle-app-enginewebapp2

google app engine ndb successive queries


Suppose I have an HTML form as follows:

<form ...>
    Title: <input type=text name=title>
    Account: <input type=text name=account>
    <input type=submit value=search>
</form>

The NDB of the google app engine is as follows:

class Message(ndb.Model):
    title = ndb.StringProperty()
    account = ndb.StringProperty()

Since the user may or may not input data in the fields, the search would be implemented as successive queries:

messages = Message.query()
if title:
    messages = messages.query(Message.title==title)
if account:
    messages = messages.query(Message.account==account)

The above code didn't work because "Query object has no attribute query"

So, how do I perform successive queries?


Solution

  • Have you read the docs for ndb queries. https://developers.google.com/appengine/docs/python/ndb/queries

    It has a good example of constructing a query in multiple parts

    qry1 = Account.query() # Retrieve all Account entitites
    qry2 = qry1.filter(Account.userid >= 40) # Filter on userid >= 40
    qry3 = qry2.filter(Account.userid < 50) # Filter on userid < 50 as well
    

    In your example you would

    messages = Message.query()
    if title:
        messages = messages.filter(Message.title==title)
    if account:
        messages = messages.filter(Message.account==account)
    

    Calling query() in the code you have in the question creates a new query, rather than extending it.

    Read further in the docs, and you can see you can also start using OR operators to construct the query in multiple phases. The example above means AND.