SQLAlchemy equivalent to SQL "LIKE" statement

PythonSqlalchemy

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

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

Solution 2 - Python

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.

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

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

For more info go Common Filter Operators

Solution 3 - Python

try this code

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

Solution 4 - Python

In case you want the case insensitive like clause implementation:

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

Solution 5 - Python

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()

Solution 6 - Python

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

Solution 7 - Python

In SQLAlchemy 1.4/2.0:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGary OldfaberView Question on Stackoverflow
Solution 1 - PythonDaniel KluevView Answer on Stackoverflow
Solution 2 - PythonigsmView Answer on Stackoverflow
Solution 3 - Pythonwaruna kView Answer on Stackoverflow
Solution 4 - PythonPrason GhimireView Answer on Stackoverflow
Solution 5 - PythonTobyView Answer on Stackoverflow
Solution 6 - Pythonkoks der dracheView Answer on Stackoverflow
Solution 7 - PythoncollinsmarraView Answer on Stackoverflow