Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 963
allenlin1992 Avatar asked Feb 08 '23 08:02

allenlin1992


1 Answers

use having()

from sqlalchemy import func

session.query(Parent).\
        join(Parent.children).\
        group_by(Parent).\
        having(func.count(Child.id) > 1)
like image 192
r-m-n Avatar answered Feb 11 '23 07:02

r-m-n