Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions in SQLalchemy queries?

Is it possible to use a regex in a way similar to session.query(MyObject).filter_by(REGEX)?

If not, how can I use sqlAlchemy to retrieve records that have a varchar PK beginning with a certain value (e.g. all those whose city field begins with "SA")? Thanks.

like image 745
dpq Avatar asked Nov 06 '10 07:11

dpq


4 Answers

I think I got it:

session.query(Object).filter(Object.column.op('regexp')(REGEX))
like image 175
dpq Avatar answered Oct 14 '22 01:10

dpq


For the record, you can do essentially the same syntax as Paulo Scardine's answer in SQLAlchemy too;

session.query(Object).filter(Object.column.like('something%'))
like image 40
Alex Avatar answered Oct 14 '22 01:10

Alex


as of SqlAlchemy 1.4, there's a built-in regular expression operator, regexp_match.

like image 7
Todd Jacobus Avatar answered Oct 13 '22 23:10

Todd Jacobus


[DISCLAIMER: no regex]

I'm answering to the question "how can I use sqlAlchemy to retrieve records that have a varchar PK beginning with a certain value" because for this simple use case a LIKE probably is both less expensive and more portable (asking for regular expressions seems like a manifestation of the XY Problem).

In SQLAlquemy (borrowing from Alex):

session.query(Object).filter(Object.column.like('something%'))

In SqlSoup I use:

db.table.filter(db.table.column.like('something%')) 
like image 3
Paulo Scardine Avatar answered Oct 14 '22 00:10

Paulo Scardine