1 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
多虧了 github 上的 zzzeek,我找到了答案:別名在第二次嵌套后在子查詢中隱藏。如果我們不想要這個(gè),我們使用相關(guān)的子查詢。
固定單元測試:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, aliased
from sqlalchemy import Column, Integer, create_engine, literal
_sql_engine = create_engine('sqlite:///:memory:')
session = sessionmaker(bind=_sql_engine)()
def test_model():
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
class C(Base):
__tablename__ = 'c'
a = Column(Integer, primary_key=True)
b = Column(Integer, primary_key=True)
Base.metadata.create_all(_sql_engine)
a = [A(id=10), A(id=20)]
c = [C(a=10, b=11), C(a=20, b=21)]
b = [B(id=11)]
session.add_all(a + c + b)
session.commit()
q = session.query(A).filter(
A.id < literal(100),
~(
session.query(C)
.filter(
A.id == C.a,
~(
session.query(B)
.filter(
B.id == C.b
).exists().correlate(A,C)
)
).exists()
)
)
print(q.statement)
print(len(q.all()))
assert len(q.all()) == 1
添加回答
舉報(bào)