我的表格有enemy_one
,fight_id
和enemy_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()
通过这种方式,我得到了所有的打斗,但有一种方法可以将这两个查询绑定在一起吗?
答案 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()