[英]SQLAlchemy filter query “column LIKE ANY (array)”
Hi SQLAlchemy experts out there, here's a tricky one for you:嗨 SQLAlchemy 专家,这里有一个棘手的问题:
I'm trying to write a query that resolves into something like:我正在尝试编写一个解析为以下内容的查询:
SELECT * FROM MyTable where my_column LIKE ANY (array['a%', 'b%'])
using SQLAlchemy:使用 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)
Any solutions?任何解决方案?
Use or_() and like()
, the following code should satisfy your need well:使用or_()和like()
,以下代码应该可以很好地满足您的需求:
from sqlalchemy import or_
foo = ['a%', 'b%']
DBSession().query(MyTable).filter(or_(*[MyTable.my_column.like(name) for name in foo]))
A where condition WHERE my_column LIKE 'a%' OR my_column LIKE 'b%'
would be generated from above code.一个 where 条件WHERE my_column LIKE 'a%' OR my_column LIKE 'b%'
将从上面的代码生成。
As for why your any()
didn't work, I think it's because it requires my_column
to be a list (see here ), and, for instance, query(MyTable).filter(MyTable.my_list_column.any(name='abc'))
is to return MyTable
rows if any element in my_list_column
column (a list) of that row is named with 'abc', so it's actually quite different from your need.至于为什么你的any()
不起作用,我认为这是因为它需要my_column
是一个列表(见这里),例如, query(MyTable).filter(MyTable.my_list_column.any(name='abc'))
如果该行的my_list_column
列(列表)中的任何元素以 'abc' 命名,则返回MyTable
行,因此它实际上与您的需要大不相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.