39

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 contain some 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?

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

3 Answers 3

77

I think it should work

Post.query.filter(Post.title.ilike('%some_phrase%'))

http://docs.sqlalchemy.org/en/latest/orm/internals.html?highlight=ilike#sqlalchemy.orm.attributes.QueryableAttribute.ilike

Sign up to request clarification or add additional context in comments.

2 Comments

Does this affect performance compared to the more restricted like() function?
It depends on an engine you use: PostgreSQL, MySQL or else. SQLAlchemy is just a wrapper for SQL.
26

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

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

Comments

4

There is another workable solution:

from sqlalchemy.sql.operators import ilike_op
Post.query.filter(ilike_op(Post.title, f'%{some_phrase}%'))

This solution helped me to overcame the warning Unresolved attribute reference 'ilike' for class 'property' when I used hybrid_property

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.