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?
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With