0

I'm trying to match some names with the names I already have in my Postgresql database, using the following code:

last_like = '{last_name}%'.format(last_name)
matches = Session.query(MyTable).filter(or_(
    MyTable.name.ilike(last_like),
    MyTable.other_names.any(last_like, operator=ilike_op),
)).all()

Essentially it tries to match the name column or any of the other names stored as an array in the other_names column.

But I get:

KeyError: <function ilike_op at 0x7fb5269e2500>

What am I doing wrong?

Pardeep Dhingra
  • 3,916
  • 7
  • 30
  • 56
bard
  • 2,762
  • 9
  • 35
  • 49

1 Answers1

1

For use postgresql array field you need to use unnest() function. But you can't use result of unnest() in where clause.

Instead, you can use array_to_string function. Searching on string of other_names will give the same effect

from sqlalchemy import func as F
last_like = "%qq%"
matches = session.query(MyTable).filter(or_(
    MyTable.name.ilike(last_like),
    F.array_to_string(MyTable.other_names, ',').ilike(last_like),
)).all()
Danil
  • 4,781
  • 1
  • 35
  • 50