我想将以下原始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))
有人可以帮忙吗? 提前致谢
答案 0 :(得分:19)
kw_id
此处似乎是一个标量列值,因此您无法调用any()
- any()
只能从relationship()绑定属性中获取。由于我在这里没有看到其中一个,你可以直接拨打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
)
)
)