Python SQLAlchemy 等效于 SQL "LIKE" 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3325467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:27:46  来源:igfitidea点击:

SQLAlchemy equivalent to SQL "LIKE" statement

pythonsqlalchemy

提问by Gary Oldfaber

A tags column has values like "apple banana orange" and "strawberry banana lemon". I want to find the SQLAlchemy equivalent statement to

标签列具有“苹果香蕉橙”和“草莓香蕉柠檬”等值。我想找到 SQLAlchemy 等效语句

SELECT * FROM table WHERE tags LIKE "%banana%";

What should I pass to Class.query.filter()to do this?

我应该通过什么Class.query.filter()来做到这一点?

采纳答案by Daniel Kluev

Each column has like()method, which can be used in query.filter(). Given a search string, add a %character on either side to search as a substring in both directions.

每列都有like()方法,可以在query.filter(). 给定一个搜索字符串,%在任一侧添加一个字符以作为两个方向的子字符串进行搜索。

tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()

回答by igsm

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

添加到上面的答案中,无论谁寻找解决方案,您也可以尝试使用“匹配”运算符而不是“喜欢”。不想有偏见,但它在 Postgresql 中对我来说非常有效。

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINSand MATCH. However, it is not available in SQLite.

它继承了CONTAINSMATCH等数据库功能。但是,它在 SQLite 中不可用。

For more info go Common Filter Operators

有关更多信息,请访问Common Filter Operators

回答by waruna k

try this code

试试这个代码

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

回答by konstantin

Using PostgreSQL like(see accepted answer above) somehow didn't work for me although cases matched, but ilike(case insensisitive like) does.

使用 PostgreSQL like见上面接受的答案)不知何故对我不起作用,尽管案例匹配,但ilike(案例nsensisitive like)确实如此。