Skip to content Skip to sidebar Skip to footer

Sqlalchemy How To Filter By Children In Many To Many

I was asking for a problem I had in SQLAlchemy and found the solution while writing. I post it anyway just in case it helps somebody :) Let's say I have a many to many relationship

Solution 1:

query = (
    session.query(Post)
           .join(Post.tags)     # It's necessary to join the "children" of Post
           .filter(Post.date_out.between(start_date, end_date))
           # here comes the magic: # you can filter with Tag, even though it was not directly joined)
           .filter(Tag.accepted == 1)
)

Disclaimer: this is a veeery reduced example of my actual code, I might have made a mistake while simplifying.

I hope it helps somebody.

Post a Comment for "Sqlalchemy How To Filter By Children In Many To Many"