How to write multi column in clause with sqlalchemy

前端 未结 3 1147
时光取名叫无心
时光取名叫无心 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:24

    I ended up using the test() based solution: generated "(a,b) in ((:a1, :b1), (:a2,:b2), ...)" with named bind vars and generating dictionary with bind vars' values.

    params = {}
    for counter, r in enumerate(records):
        a_param = "a%s" % counter
        params[a_param] = r['a']
        b_param = "b%s" % counter
        params[b_param] = r['b']
        pair_text = "(:%s,:%s)" % (a_param, b_param)
        enum_pairs.append(pair_text)
    multicol_in_enumeration = ','.join(enum_pairs)
    multicol_in_clause = text(
        " (a,b) in (" + multicol_in_enumeration + ")")
    q = session.query(Table.id, Table.a,
                                Table.b).filter(multicol_in_clause).params(params)
    

    Another option I thought about using mysql upserts but this would make whole included even less portable for the other db engine then using multicolumn in clause.

    Update SQLAlchemy has sqlalchemy.sql.expression.tuple_(*clauses, **kw) construct that can be used for the same purpose. (I haven't tried it yet)

提交回复
热议问题