4

By "reverse version of like" I mean exactly like this question. The question is how to make a query like that in sqlalchemy?

I found out that to make "SELECT LIKE" query in sqlalchemy I should make something like that

session.query(Book).filter(Book.title.like("%"+my_title+"%"))

Because like is method of column, I don't know how to use like method to ask about "%" + Book.title + "%".

Community
  • 1
  • 1
noisy
  • 6,495
  • 10
  • 50
  • 92
  • @Spudley That question is about a NOT LIKE operator, this question is about reversing the relationship between the column and the pattern. – Barmar Mar 29 '13 at 22:23
  • 2
    So if `Book.title` contains "blah" you want the query to succeed when `my_title` contains "Something with blah in it", right? – Barmar Mar 29 '13 at 22:28
  • @Spudley: this is not a duplicate of your question. – noisy Mar 29 '13 at 23:33

1 Answers1

3

Thanks to this question, I figure out how to do that :)

session.query(Book).
    filter(bindparam('book_title', book.title).contains(Book.title)).first()
Community
  • 1
  • 1
noisy
  • 6,495
  • 10
  • 50
  • 92
  • 2
    `literal(book.title)` is a shortcut for that bindparam() – zzzeek Mar 30 '13 at 20:52
  • Thank you! I was looking for exactly this. Both the bindparam() and literal() approach works. Can you please explain what is happening under the hood which makes this approach work? Thanks! – Amogh Mishra Dec 28 '21 at 18:33