sqlalchemy - 加入包含2个条件的子表

时间:2012-06-21 18:32:13

标签: python sqlalchemy

如何在连接2个表时向ON子句添加2个条件。 我有3个三层表,每个表都有删除标志。我必须在单个查询中加入所有这些表,并根据已删除的标志进行过滤。目前,条件被添加到查询的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()

三江源

3 个答案:

答案 0 :(得分:26)

尝试使用contains_eager而不是joinedload。可能发生的是你用连接定义了两个连接,然后是选项中的两个连接(joinedload(...))

修改你的代码,应该给出:

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()
)

答案 1 :(得分:6)

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

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(joinedload('switches')).
    options(joinedload('ports')).
    all()
)

答案 2 :(得分:5)

The and_() conjunction is also available using the Python & operator(虽然请注意复合表达式需要括起来以便使用Python运算符优先级行为): 还有| for or_()~ for not_()

所以使用&运算符您的代码将如下所示:

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()
)
相关问题