5

I am using sqlalchemy to fetch data from tables. Right now fetching all records from a table called audit_trail_table is working as expected.

select_stmt = select([self.audit_trail_table]).where(self.audit_trail_table.c.id == int(id))
row = conn.execute(select_stmt).fetchone()

Now I wish to execute LIKE queries on multiple columns as follows:

filter_query = #(some value which will work as a filter_query while fetching )records
filter_stmt = select([self.audit_trail_table]).where(self.audit_trail_table.c.first_name like '%' + filter_query + '%' or self.audit_trail_table.c.last_name like '%')

But it gives an error at LIKE. How can I achieve this?

Nilesh
  • 20,521
  • 16
  • 92
  • 148
exAres
  • 4,806
  • 16
  • 53
  • 95

1 Answers1

7

You can use the like operator:

select([self.audit_trail_table]).where(
    self.audit_trail_table.c.first_name.like('%' + filter_query + '%') or 
    self.audit_trail_table.c.last_name.like('%abc%')
)
Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • It is working for a single `like()`. But I am getting an error when I combine two `like()` functions with `or` as : `TypeError: Boolean value of this clause is not defined` – exAres Jul 18 '14 at 11:20
  • u have to use OR operator from django instead of OR operator from python – Nilesh Jul 18 '14 at 11:38
  • 1
    Yes. I have used `or_()` from sqlalchemy instead. Thanks a lot for your help ! – exAres Jul 18 '14 at 11:43
  • 3
    You can also use [`contains`](http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.contains) in place of `like` – RedBaron Jul 22 '14 at 12:20
  • @RedBaron That should be an answer, not hidden in the comments section! – pydsigner Jun 02 '16 at 03:30