Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

SA has support for regexes but those seem to be Python regexps (Regular expressions in SQLalchemy queries?)

I need to use regex on matching some rows (a row contains 1 log line, so regex is a natural match) but for performance reasons I would prefer to do it using PG backend, like in this question:

select * from table where name ~ 'foo';

How can I combine both PG-implemented regex AND SQLAlchemy object selection in one query?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The filter() method of the Query object allows for you to use raw SQL for the filter. So, you could do...

Table.query.filter("name ~ 'foo'")

Note that if you want to provide this as an argument, you can use text() and params()...

from sqlalchemy.sql import text

Table.query.filter(text('name ~ :reg')).params(reg='foo')

Because we define the "reg" bind parameter in the filter using text(), we need to make sure we define the value, which we can do using params().

share|improve this answer
    
Thank you!! This thing with bind parameters is also very useful (protection against sql injection and the like). –  John Doe Nov 26 '13 at 9:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.