How to write multi column in clause with sqlalchemy

前端 未结 3 1137
时光取名叫无心
时光取名叫无心 2020-12-16 03:57

Please suggest is there way to write query multi-column in clause using SQLAlchemy?

Here is example of the actual query:

SELECT  url FROM pages WHERE         


        
3条回答
  •  借酒劲吻你
    2020-12-16 04:13

    I do not think this is currently possible in sqlalchemy, and not all RDMBS support this.
    You can always transform this to a OR(AND...) condition though:

    filter_rows = [
        (2752937066, 'http://members.aye.net/~gharris/blog/'),
        (3799762538, 'http://www.coxandforkum.com/'),
        ]
    qry = session.query(Page)
    qry = qry.filter(or_(*(and_(Page.url_crc == crc, Page.url == url) for crc, url in filter_rows)))
    print qry
    

    should produce something like (for SQLite):

    SELECT  pages.id AS pages_id, pages.url_crc AS pages_url_crc, pages.url AS pages_url
    FROM    pages
    WHERE   pages.url_crc = ? AND pages.url = ? OR pages.url_crc = ? AND pages.url = ?
    -- (2752937066L, 'http://members.aye.net/~gharris/blog/', 3799762538L, 'http://www.coxandforkum.com/')
    

    Alternatively, you can combine two columns into just one:

    filter_rows = [
        (2752937066, 'http://members.aye.net/~gharris/blog/'),
        (3799762538, 'http://www.coxandforkum.com/'),
        ]
    qry = session.query(Page)
    qry = qry.filter((func.cast(Page.url_crc, String) + '|' + Page.url).in_(["{}|{}".format(*_frow) for _frow in filter_rows]))
    print qry
    

    which produces the below (for SQLite), so you can use IN:

    SELECT  pages.id AS pages_id, pages.url_crc AS pages_url_crc, pages.url AS pages_url
    FROM    pages
    WHERE   (CAST(pages.url_crc AS VARCHAR) || ? || pages.url) IN (?, ?)
    -- ('|', '2752937066|http://members.aye.net/~gharris/blog/', '3799762538|http://www.coxandforkum.com/')
    

提交回复
热议问题