use*_*438 12 python sqlalchemy any
您好SQLAlchemy专家,这里有一个棘手的问题:
我正在尝试编写一个解析为以下内容的查询:
SELECT * FROM MyTable where my_column LIKE ANY (array['a%', 'b%'])
Run Code Online (Sandbox Code Playgroud)
使用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)
Run Code Online (Sandbox Code Playgroud)
有解决方案吗
Pau*_* Lo 21
使用or_()和like(),以下代码应该满足您的需求:
from sqlalchemy import or_
foo = ['a%', 'b%']
DBSession().query(MyTable).filter(or_(*[MyTable.my_column.like(name) for name in foo]))
Run Code Online (Sandbox Code Playgroud)
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',所以它实际上与你的需求完全不同.
小智 9
您可以尝试使用any_()
在您的情况下,它看起来像这样:
from sqlalchemy import any_
foo = ['a%', 'b%']
DBSession().query(MyTable).filter(MyTable.my_column.like(any_(foo)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9788 次 |
| 最近记录: |