PostgreSQL ILIKE 查询与 SQLAlchemy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20363836/
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-10-21 01:13:06  来源:igfitidea点击:

PostgreSQL ILIKE query with SQLAlchemy

pythonpostgresqlsqlalchemyflaskflask-sqlalchemy

提问by sundance

I'd like to run a query that selects all posts, case insensitive, that have titles that match '%' + [some_phrase] + '%'. That is, select all rows that have titles that containsome phrase, case insensitive. From the research I've done, it looks like I need to use Postgres's ILIKE query for it to match case insensitive. How can I execute a query like this with SQLAlchemy?

我想运行一个查询来选择所有帖子,不区分大小写,标题匹配'%' + [some_phrase] + '%'. 也就是说,选择标题中包含一些短语的所有行,不区分大小写。根据我所做的研究,看起来我需要使用 Postgres 的 ILIKE 查询来匹配不区分大小写的。如何使用 SQLAlchemy 执行这样的查询?

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(250))
    content = db.Column(db.String(5000))

回答by Anatoly E

For python 3.6 instead of '%' + some_phrase + '%'you can write

对于 python 3.6 而不是'%' + some_phrase + '%'你可以写

Post.query.filter(Post.title.ilike(f'%{some_phrase}%'))