Search code examples
pythonsqlsqlalchemymany-to-many

SQLAlchemy many to many filter rows by number of children


What is the best way to retrieve all the rows in a table (that is part of many to many) with more than one child? I have tried:

session.query(Parent).filter(len(Parent.children)>1).all() 

but I get error 'object of type 'InstrumentedAttribute' has no len()'. I have been able to get all Parents with at least one child using:

session.query(Parent).filter(Parent.children).all()

Solution

  • use having()

    from sqlalchemy import func
    
    session.query(Parent).\
            join(Parent.children).\
            group_by(Parent).\
            having(func.count(Child.id) > 1)