SQLAlchemy equivalent to SQL “LIKE” statement

前端 未结 5 646
借酒劲吻你
借酒劲吻你 2020-12-02 21:50

A tags column has values like \"apple banana orange\" and \"strawberry banana lemon\". I want to find the SQLAlchemy equivalent statement to

SELECT * FROM ta         


        
相关标签:
5条回答
  • 2020-12-02 22:11

    If you use native sql, you can refer to my code, otherwise just ignore my answer.

    SELECT * FROM table WHERE tags LIKE "%banana%";
    
    from sqlalchemy import text
    
    bar_tags = "banana"
    
    # '%' attention to spaces
    query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
    
    # db is sqlalchemy session object
    tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
    
    
    0 讨论(0)
  • 2020-12-02 22:15

    Using PostgreSQL like (see accepted answer above) somehow didn't work for me although cases matched, but ilike (case insensisitive like) does.

    0 讨论(0)
  • 2020-12-02 22:22

    Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

    Note.query.filter(Note.message.match("%somestr%")).all()
    

    It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

    For more info go Common Filter Operators

    0 讨论(0)
  • 2020-12-02 22:28

    try this code

    output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))
    
    0 讨论(0)
  • 2020-12-02 22:34

    Each column has like() method, which can be used in query.filter(). Given a search string, add a % character on either side to search as a substring in both directions.

    tag = request.form["tag"]
    search = "%{}%".format(tag)
    posts = Post.query.filter(Post.tags.like(search)).all()
    
    0 讨论(0)
提交回复
热议问题