作者:Devil灬旋律 | 来源:互联网 | 2023-05-23 21:27
您好SQLAlchemy专家,这里有一个棘手的问题:
我正在尝试编写一个解析为以下内容的查询:
SELECT * FROM MyTable where my_column LIKE ANY (array['a%', 'b%'])
使用SQLAlchemy:
foo = ['a%', 'b%']
# this works, but is dirty and silly
DBSession().query(MyTable).filter("my_column LIKE ANY (array[" + ", ".join(["'" + f + "'" for f in token.tree_filters]) + "])")
# something like this should work (according to documentation), but doesn't (throws "AttributeError: Neither 'AnnotatedColumn' object nor 'Comparator' object has an attribute 'any'"
DBSession().query(MyTable).filter(MyTable.my_column.any(foo, operator=operators.like)
有解决方案吗
1> Paul Lo..:
使用or_()和like()
,以下代码应该满足您的需求:
from sqlalchemy import or_
foo = ['a%', 'b%']
DBSession().query(MyTable).filter(or_(*[MyTable.my_column.like(name) for name in foo]))
WHERE my_column LIKE 'a%' OR my_column LIKE 'b%'
将从上面的代码生成where条件.
至于为什么你any()
没有工作,我认为这是因为它需要my_column
是一个列表(见这里),例如,如果该行的列(列表)中的任何元素以'abc命名,query(MyTable).filter(MyTable.my_list_column.any(name='abc'))
则返回MyTable
行my_list_column
',所以它实际上与你的需求完全不同.