I want to convert the following raw sql query into a sqlalchemy ORM query :
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);
I tried the following ORM query but didn't succeed:
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))
Can anyone please help? Thanks in advance
kw_id
here seems to be a scalar column value, so you can't call any()
on that - any()
is only available from a relationship() bound attribute. Since I don't see one of those here you can call the exists() directly:
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
)
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With