I am trying to implement a select with a nested select clause, to find parents without any children. My tables (radically simplified) are as follows:
class Pers
Using a subquery:
sub_stmt = config.Session.query(ChildTable.person_id)
stmt = config.Session.query(Person).filter(~Person.id.in_(sub_stmt))
empty_persons = stmt.all()
emits the following sql:
SELECT person.id AS person_id, person.name AS person_name
FROM person
WHERE person.id NOT IN (SELECT foo.person_id AS foo_person_id
FROM foo)
Using a join:
stmt = config.Session.query(Person).outerjoin(ChildTable).filter(ChildTable.person_id.is_(None))
empty_persons = stmt.all()
emits the following sql:
SELECT person.id AS person_id, person.name AS person_name
FROM person LEFT OUTER JOIN foo ON person.id = foo.person_id
WHERE foo.person_id IS NULL
I think both achieve your desired result set.