Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL ILIKE query with SQLAlchemy

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)) 
like image 668
sundance Avatar asked Dec 03 '13 23:12

sundance


People also ask

Can I use SQLAlchemy with Postgres?

Install a Postgres server locally and create a database. Use Python with SQLAlchemy to connect to the database and create tables. Use Python with SQLAlchemy to insert data and query the database.

How do I use Ilike in PostgreSQL?

The keyword ILIKE can be used instead of LIKE to make the match case insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. The operator ~~ is equivalent to LIKE , and ~~* corresponds to ILIKE .

What is the difference between like and Ilike in PostgreSQL?

LIKE and ILIKE allow pattern matching within character-based column data. Their syntax is identical, but LIKE is case-sensitive, while ILIKE is case-insensitive.

How do I run a SQLAlchemy query?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.


2 Answers

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

like image 169
user1454592 Avatar answered Sep 21 '22 22:09

user1454592


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

Post.query.filter(Post.title.ilike(f'%{some_phrase}%')) 
like image 35
Anatoly E Avatar answered Sep 20 '22 22:09

Anatoly E