python - SQLAlchemy, select such A that has at least one B with raised flag -


i have 2 tables:

class a(base):     id = column(integer, primary_key=true)  class b(base):     id = column(integer, primary_key=true)      a_id = column(integer, foreignkey('a.id'))     = relationship(a)     flag = column(boolean, default=false) 

as can see - each object b related 1 object a, also, more 1 object b can related single object a.
need select a's have @ least 1 related b flag == false.
i'm thinking on this:

    selection = session.query(a).\         join(b).\         filter(             b.a_id == a.id,             b.flag == false,         ).\         group_by(a) 

but i'm not sure 2 things:

  1. if query correct? (i'm working huge amounts of data , it's quite complicated test out).

  2. if query correct point of sqlalchemy philosophy? (i'm newbie it).

add backref relationship:

class b(base):     # ...     = relationship(a, backref="b_s") 

then sqlalchemy verino of @erwin's sql version below:

qry = session.query(a).filter(a.b_s.any(b.flag == false)) 

if not want or cannot add backref relationship, below produce same query simple case, should keep eye on generated sql in case have more complicated queries joins might need more tweaking:

qry = (session.query(a).filter(     exists(select([1]).where(b.a_id == a.id).where(b.flag == false))) ) 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -