SQLAlchemy equivalent to SQL "LIKE" statement

Viewed 149669

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

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

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

8 Answers

In case you want the case insensitive like clause implementation:

session.query(TableName).filter(TableName.colName.ilike(f'%{search_text}%')).all()

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

In SQLAlchemy 1.4/2.0:

q = session.query(User).filter(User.name.like('e%'))

Doing it like this worked for me (Oracle) as native sql

"SELECT * FROM table WHERE tags LIKE '%' || :bar_tags || '%' "
Related