[英]In Sql Alchemy, how to select rows where any column contains a substring?
I want to retrieve all the rows of a table where a substring "h" is contained in any of the columns)我想检索任何列中包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ“h”的表的所有行)
I tried something like this:我试过这样的事情:
list_of_columns = [c for c in my_table.columns] # where my_table is of class Table
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
list_of_columns.contains(q),
))
Of course this does not work, as " contains() " should be called on a single column...当然这不起作用,因为应该在单个列上调用“ contains() ”......
Any idea?任何想法?
ps: the retrieving of the columns must be dynamic, this is the way my code must work ps:列的检索必须是动态的,这是我的代码必须工作的方式
[EDIT] [编辑]
An almost working solution:一个几乎可行的解决方案:
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
or_(
list_of_columns[0].contains(q),
list_of_columns[1].contains(q),
...
)
))
But, I need the listing of the columns to be dynamic但是,我需要列的列表是动态的
You can use a list comprehension to add all the columns to the query:您可以使用列表推导将所有列添加到查询中:
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
or_(*[col.contains(q) for col in list_of_columns])
))
For this kind of search, you might also get better performance and results by using postgresql's full-text search functionality, and creating a tsvector that combines all of the columns: https://stackoverflow.com/a/42390204/16811479对于这种搜索,您还可以通过使用 postgresql 的全文搜索功能并创建一个组合所有列的 tsvector 来获得更好的性能和结果: https://stackoverflow.com/a/42390204/16811479
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.