Search code examples
pythonsqlalchemysql-like

Use variable in sqlalchemy ilike statement


I am trying to query my database to find all items that match my variable received_input.

At the moment I have:

session.query(VenueItem).filter(VenueItem.venue_item_name.ilike("%received_input%")).all()

The items in my database may contain uppercase and lowercase characters. I need to ensure that the search is case-insensitive ("ApPle" would return from input of "apple").

I don't know the syntax to specify a variable in ilike as opposed to a string.


Solution

  • Replace "%received_input%" with

    '%{}%'.format(received_input)
    

    On python 3.6+, this can be written more concisely using f-strings:

    Example:

    f'%{received_input}%'