问题
I have the following query in my application
query = cls.query().filter(cls.taskgroup_id == taskgroup_id, cls.availability == True, cls.task_id > min_task_id).order(cls.task_id)
query.fetch(1)
Above works fine as expected. (Fetches only those entities, which match taskgroup_id, and is available, and task_id > min_task_id)
However, when I break query into multiple statements.
query = cls.query()
query.filter(cls.taskgroup_id == taskgroup_id)
query.filter(cls.availability == True)
query.filter(cls.task_id > min_task_id)
It doesn't work as expected.
When I run [2], query formation broken down into multiple statements, it returns me a entity whose availability is False, and task_id is equal to min_task_id.
[2] doesn't work as expected (or as I expect). I think there is a user error here. Wondering what it is.
回答1:
From Filtering by Property Values (emphasis mine):
query = Account.query(Account.userid >= 40, Account.userid < 50)[...]
Instead of specifying an entire query filter in a single expression, you may find it more convenient to build it up in steps: for example:
appengine/standard/ndb/queries/snippets.py
query1 = Account.query() # Retrieve all Account entitites query2 = query1.filter(Account.userid >= 40) # Filter on userid >= 40 query3 = query2.filter(Account.userid < 50) # Filter on userid < 50 too
query3is equivalent to thequeryvariable from the previous example. Note that query objects are immutable, so the construction ofquery2does not affectquery1and the construction ofquery3does not affectquery1orquery2.
In other words for your example none of the query.filter() statements actually modifies query.
Just assign the results of the statements to local variables and use those instead, just as in the quoted example.
来源:https://stackoverflow.com/questions/40689781/ndb-query-builder-doesnt-work-as-expected