繁体   English   中英

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

[英]sqlalchemy - join child table with 2 conditions

如何在连接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()

谢谢

尝试使用contains_eager而不是joinedload。 可能发生的是你有4个连接你用join定义的两个,然后是两个来自选项(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()
)

使用Python&运算符也可以使用and_()连接 (但请注意,复合表达式需要括起来以便使用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()
)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM