NDB Query builder doesn't work as expected

眉间皱痕 提交于 2019-12-24 06:47:19

问题


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

query3 is equivalent to the query variable from the previous example. Note that query objects are immutable, so the construction of query2 does not affect query1 and the construction of query3 does not affect query1 or query2.

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

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