Python sqlalchemy-使用2个条件连接子表

Python sqlalchemy-使用2个条件连接子表,python,sqlalchemy,Python,Sqlalchemy,如何在联接2个表时向ON子句添加2个条件。 我在层次结构中有三个表,每个表都有删除标志。我必须在一个查询中连接所有这些表,并根据删除标志进行筛选。当前,这些条件被添加到查询的where子句中,该子句不会过滤已删除的记录。 它需要添加到ON子句中。请建议 我目前的查询如下: result = session.query(Host).filter(and_(Host.id.in_(ids), Host.deleted == False)).\ join(Switch).filter(Swit

如何在联接2个表时向ON子句添加2个条件。 我在层次结构中有三个表,每个表都有删除标志。我必须在一个查询中连接所有这些表,并根据删除标志进行筛选。当前,这些条件被添加到查询的where子句中,该子句不会过滤已删除的记录。 它需要添加到ON子句中。请建议

我目前的查询如下:

result = session.query(Host).filter(and_(Host.id.in_(ids), Host.deleted == False)).\
    join(Switch).filter(Switch.deleted == False).\
    join(Port).filter(Port.deleted == False).\
    options(joinedload('switches')).\
    options(joinedload('ports')).\
    all()

谢谢

您可以使用
onclause
参数在调用中明确指定
ON
子句。然后您的查询应该如下所示(未测试):


Try包含渴望而不是joinedload。可能发生的情况是,您有4个join(使用join定义的两个join),然后是来自选项(joinedload(…)的两个join)

修改代码时,应提供以下信息:

from sqlalchemy import and_

result = (session.query(Host).filter(and_(Host.id.in_(ids), Host.deleted == False)).
    join(Switch, and_(Switch.host_id==Host.id, Switch.deleted == False)).
    join(Port, and_(Port.switch_id==Switch.id, Port.deleted == False)).
    options(contains_eager('switches')).
    options(contains_eager('ports')).
    all()
)
(但请注意,复合表达式需要加括号才能与Python运算符优先级行为一起工作): 还有和

因此,使用运算符(&O),您的代码将如下所示:

result = session.query(Host).filter(Host.id.in_(ids) & (Host.deleted == False)).
    join(Switch, (Switch.host_id==Host.id) & (Switch.deleted == False)).
    join(Port, (Port.switch_id==Switch.id) & (Port.deleted == False)).
    options(contains_eager('switches')).
    options(contains_eager('ports')).
    all()
)

嗨,范,这不是在结果中添加过滤器。谢谢。请打印生成的SQL查询好吗?(只需从代码中删除.all(),然后打印即可)
result = session.query(Host).filter(Host.id.in_(ids) & (Host.deleted == False)).
    join(Switch, (Switch.host_id==Host.id) & (Switch.deleted == False)).
    join(Port, (Port.switch_id==Switch.id) & (Port.deleted == False)).
    options(contains_eager('switches')).
    options(contains_eager('ports')).
    all()
)