Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy equivalent to SQL "LIKE" statement

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?

like image 932
Gary Oldfaber Avatar asked Jul 24 '10 14:07

Gary Oldfaber


People also ask

Is SQLAlchemy same as SQL?

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present.


2 Answers

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() 
like image 86
Daniel Kluev Avatar answered Sep 20 '22 12:09

Daniel Kluev


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

like image 43
igsm Avatar answered Sep 18 '22 12:09

igsm