19

我想将以下原始 sql 查询转换为 sqlalchemy ORM 查询:

SELECT * FROM kwviolations AS kwviol WHERE kwviol.proj_id=1 AND NOT EXISTS (SELECT * FROM
kwmethodmetrics AS kwmetrics WHERE kwmetrics.kw_id=kwviol.kw_id AND kwmetrics.checkpoint_id=5);

我尝试了以下 ORM 查询但没有成功:

self.session.query(KWViolations).filter(KWViolations.proj_id==project.id).\
filter(and_(~KWViolations.kw_id.any(KWMethodMetrics.kw_id==KWViolations.kw_id),KWMethodMetrics.checkpoint_id==checkpoint.id))

有人可以帮忙吗?提前致谢

4

1 回答 1

27

kw_id这里似乎是一个标量列值,所以你不能调用any()它 -any()只能从关系()绑定属性中获得。由于我在这里看不到其中之一,因此您可以直接调用exists()

from sqlalchemy import exists

session.query(KWViolations).filter(KWViolations.proj_id == project.id).\
    filter(
        ~exists().where(
                and_(
                    KWMethodMetrics.kw_id == KWViolations.kw_id,
                    KWMethodMetrics.checkpoint_id == checkpoint.id
                )
        )
    )
于 2013-01-31T00:21:48.233 回答