Sql Alchemy filter / where子句由OR加入而不是AND

时间:2017-06-11 10:16:26

标签: sqlalchemy where-clause

我想根据复合键选择一堆不同的记录。在SQL中我写了这样的东西:

SELECT * FROM security WHERE (
    exchange_code = 'exchange_code_1' AND code = 'code_1') 
    OR (exchange_code = 'exchange_code_2' AND code = 'code_2')
    ...
    OR (exchange_code = 'exchange_code_N' AND code = 'code_N')
)

使用SQLAlchemy我想使用过滤子句,如:

query = sess.query(Security)
[query.filter(
    and_(Security.exchange_code == security.exchange_code, 
    Security.code == security.code)
) for security in securities]
result = query.all()

问题是filterwhere使用AND而不是OR加入子句...是否有某种方法可以将过滤器与OR一起使用?

或者我唯一的选择是生成一堆单独的选择和UNION它们?类似的东西:

first = exchanges.pop()
query = reduce(lambda query, exchange: query.union(exchange.pk_query),
                   first.pk_query())
query.all()

1 个答案:

答案 0 :(得分:1)

使用or_

query = sess.query(Security).filter(
    or_(*(and_(Security.exchange_code == security.exchange_code, 
               Security.code == security.code)
          for security in securities)))

如果您的数据库支持,则应使用tuple_代替。