sqlalchemy exists() - 如何避免额外的 From

sqlalchemy exists() - how to avoid extra From

包含另一个 exists() 的 exists() 导致额外的 From 子句。

model.session.query(Table1.id).\
    filter(~ exists().\
         where(Table2.table1_id==Table1.id).\
         where(~ exists().\
                 where(Table3.contract_id==Table2.contract_id).\
                 where(Table3.session_id==Table1.session_id))
         )

这正在生成:

SELECT table1.id AS table1_id FROM table1
WHERE NOT (EXISTS (SELECT * FROM table2
            WHERE table2.table1_id = table1.id
            AND NOT (EXISTS (SELECT * FROM table3, table1
                     WHERE table3.contract_id = table2.contract_id
                     AND table3.session_id = table1.session_id))))

这里不需要最后"exists"中的"FROM table1"因为table1已经在最顶层的查询中了。我怎样才能强制 sqlalchemy 不添加这个额外的 "FROM table1"?

我真正想要的是:

SELECT table1.id AS table1_id FROM table1
WHERE NOT (EXISTS (SELECT * FROM table2
          WHERE table2.table1_id = table1.id
          AND NOT (EXISTS (SELECT * FROM table3
                   WHERE table3.contract_id = table2.contract_id
                   AND table3.session_id = table1.session_id))))

我想知道如何实现。 有人可以帮我吗? 使用 SQLAlchemy 0.7.9.

q = (session.query(Table1.id)
     .filter(~exists(
         select([Table2.id])
         .where(Table2.table1_id == Table1.id)
         .where(~exists(
             # changing exists to be implicit enables the 'important' below
             select([Table3.id])
             .where(Table3.contract_id == Table2.contract_id)
             .where(Table3.session_id == Table1.session_id)
             # this is important
             .correlate(Table1)
             .correlate(Table2)
             ))
     )))