如何在 Python 中按一个或多个键过滤 Google App Engine 的查询?
我有一个查询
,我可以应用 过滤
它们没有任何问题。这工作得很好:
query.filter('foo =', 'bar')
但是如果我想按 key
或键列表过滤查询怎么办?
我将它们作为 Key()
属性或作为 string
并通过尝试这样的方法,它不起作用:
query.filter('key =', 'some_key') #no success
query.filter('key IN', ['key1', 'key2']) #no success
I have a query
and I can apply filters
on them without any problem. This works fine:
query.filter('foo =', 'bar')
But what if I want to filter my query by key
or a list of keys?
I have them as Key()
property or as a string
and by trying something like this, it didn't work:
query.filter('key =', 'some_key') #no success
query.filter('key IN', ['key1', 'key2']) #no success
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然可以按键进行过滤 - 请参阅@dplouffe 的答案 - 这不是一个好主意。 “IN”子句对该子句中的每一项执行一个查询,因此您最终会执行与键一样多的查询,这是实现目标的一种特别低效的方式。
相反,使用批量获取操作,如 @Luke 文档,然后过滤掉代码中列表中不需要的任何元素。
Whilst it's possible to filter on key - see @dplouffe's answer - it's not a good idea. 'IN' clauses execute one query for each item in the clause, so you end up doing as many queries as there are keys, which is a particularly inefficient way to achieve your goal.
Instead, use a batch fetch operation, as @Luke documents, then filter any elements you don't want out of the list in your code.
您可以通过执行如下所示的 GQL 查询来过滤查询:
或
You can filter queries by doing a GQL Query like this:
or
您无法对键进行过滤。哎呀,我错了。如果您设置了索引来处理键和其他属性,则可以同时过滤它。它看起来像这样:您还可以使用
get
系列方法通过键、键 ID 或键名称来查找多个模型。您可以通过这种方式获取许多实体。我不知道确切的限制。如果任何键不存在,您将在该实体的列表中看到
None
。如果您需要过滤某些属性以及键,则必须分两步完成。通过键获取并检查属性,或者查询属性并验证键。
下面是获取后进行过滤的示例。请注意,您不使用 Query 类的
filter
方法。相反,只需过滤列表即可。You cannot filter on a Key.Oops, I was wrong about that. You can filter on a key and other properties at the same time if you have an index set up to handle it. It would look like this:You can also look up a number of models by their keys, key IDs, or key names with the
get
family of methods.You can fetch many entities this way. I don't know the exact limit. If any of the keys doesn't exist, you'll get a
None
in the list for that entity.If you need to filter on some property as well as the key, you'll have to do that in two steps. Either fetch by the keys and check for the property, or query on the property and validate the keys.
Here's an example of filtering after fetching. Note that you don't use the Query class's
filter
method. Instead just filter the list.请查看:https://developers.google。 com/appengine/docs/python/ndb/entities?hl=de#multiple
Have a look at: https://developers.google.com/appengine/docs/python/ndb/entities?hl=de#multiple