简体   繁体   中英

Count number of SQLAlchemy relationships inside a filter

I've been trying to google this but I'm only really coming up with how to retrieve the count rather than filter by it. The closest result I found was this answer , but I'm constructing the query without a session so using object_session raises UnmappedInstanceError .

Given Parent and Child models, connected by Parent.children , how could I query which parents have a certain amount of children?

I've tried session.query(Parent).filter(func.count(Parent.children)>1) , but it complains about misuse of the count function.

As I'm building the query recursively for a search function, the query is actually built up of dozens of filters, so if at all possible I'd like this to remain in a single filter.

I think something like this might work (not at all tested)

session.query(func.count(Children.parent_id))\
    .group_by(Children.parent_id)\
    .filter(func.count(Children.parent_id) > 5)

After comparing the generated SQL with what is actually needed, I noticed it needed a nested select statement, which can be done with sqlalchemy.select .

Instead of this:

session.query(Parent).filter(func.count(Parent.children)>1)

The correct syntax is this:

subsearch = select([func.count(Parent.children)]).where(Parent.row_id==Child.parent_id).as_scalar()
session.query(Parent).filter(subsearch>1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM