如何在循环中使用ndb.OR?
How to use ndb.OR in a loop?
ndb.OR的正确用法是这样的:
q = News.query(ndb.OR(News.source == 'GRD', News.source == 'IND'))
这会导致 OR 过滤器。
Query(kind='News', filters=OR(FilterNode('source', '=', 'GRD'),
FilterNode('source', '=', 'IND')))
但是我如何循环执行此操作?
当我尝试这个时:
q = News.query()
for source in sources:
q = q.filter(ndb.OR(News.source == source))
它成为一个 AND 过滤器:
Query(kind='News', filters=AND(FilterNode('source', '=', 'GRD'),
FilterNode('source', '=', 'IND')))
当您重复应用这样的过滤器时,您就是在链接过滤器,每个过滤器都会过滤已经过滤的结果。
要按 sources
中的任何一个进行过滤,您可以使用 IN
。引用自 the docs:
Similarly, the IN operation
property IN [value1, value2, ...]
which tests for membership in a list of possible values, is implemented as
(property == value1) OR (property == value2) OR ...
所以你可以这样做:
qry = News.query(News.source.IN(sources))
ndb.OR的正确用法是这样的:
q = News.query(ndb.OR(News.source == 'GRD', News.source == 'IND'))
这会导致 OR 过滤器。
Query(kind='News', filters=OR(FilterNode('source', '=', 'GRD'), FilterNode('source', '=', 'IND')))
但是我如何循环执行此操作?
当我尝试这个时:
q = News.query()
for source in sources:
q = q.filter(ndb.OR(News.source == source))
它成为一个 AND 过滤器:
Query(kind='News', filters=AND(FilterNode('source', '=', 'GRD'), FilterNode('source', '=', 'IND')))
当您重复应用这样的过滤器时,您就是在链接过滤器,每个过滤器都会过滤已经过滤的结果。
要按 sources
中的任何一个进行过滤,您可以使用 IN
。引用自 the docs:
Similarly, the IN operation
property IN [value1, value2, ...]
which tests for membership in a list of possible values, is implemented as
(property == value1) OR (property == value2) OR ...
所以你可以这样做:
qry = News.query(News.source.IN(sources))