SqlAlchemy如何查询列A == a和B == b和A == b和B == a

时间:2016-12-13 19:57:06

标签: python sqlalchemy

我的表格有enemy_onefight_idenemy_two

问题是,有时enemy_two变为enemy_one,反之亦然。

我能做到:

session.query(Fight.fight_id).filter(Fight.enemy_one=='Jack', Fight.enemy_two=='Fat Chinese').all()

然后:

session.query(Fight.fight_id).filter(Fight.enemy_one=='Fat Chinese', Fight.enemy_two=='Jack').all()

通过这种方式,我得到了所有的打斗,但有一种方法可以将这两个查询绑定在一起吗?

2 个答案:

答案 0 :(得分:1)

使用in_子句:

def get_fights(enemy_one, enemy_two):
    return (
        session
        .query(Fight)
        .filter(Fight.enemy_one.in_([enemy_one, enemy_two]))
        .filter(Fight.enemy_two.in_([enemy_one, enemy_two]))
        .filter(Fight.enemy_one != Fight_enemy_two)
    )

使用or_子句:

def get_fights(enemy_one, enemy_two):
    return (
        session
        .query(Fight)
        .filter(or_(
            and_(Fight.enemy_one == enemy_one, Fight.enemy_two == enemy_two),
            and_(Fight.enemy_one == enemy_two, Fight.enemy_two == enemy_one),
        ))
    )

答案 1 :(得分:0)

随意使用sqlalchemy的函数or_()和过滤器运算符in_,如下所示:

from sqlalchemy import or_

enemies = ['Fat Chinese', 'Jack']

session.query(Fight.fight_id).filter(
    or_(
        Fight.enemy_one.in_(enemies),
        Fight.enemy_two.in_(enemies)
       )).all()