Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NOT EXISTS clause in sqlalchemy ORM query

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

like image 884
Sumedh Sidhaye Avatar asked Jan 30 '13 09:01

Sumedh Sidhaye


1 Answers

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
                )
        )
    )
like image 192
zzzeek Avatar answered Sep 18 '22 14:09

zzzeek