Giovanni Mascellani
Giovanni Mascellani

Reputation: 1278

SQL Alchemy: Relationship with grandson

I'm building a SQL Alchemy structure with three different levels of objects; for example, consider a simple database to store information about some blogs: there are some Blog object, some Post object and some Comment objects. Each Post belongs to a Blog and each Comment belongs to a Post. Using backref I can automatically have the list of all Posts belonging to a Blog and similarly for Comments.

I drafted a skeleton for such a structure.

What I would like to do now is to have directly in Blog an array of all the Comments belonging to that Blog. I've tried a few approaches, but they don't work or even make SQL Alchemy cry in ways I can't fix. I'd think that mine is quite a frequent need, but I couldn't find anything helpful.

Colud someone suggest me how to do that?

Thanks.

Upvotes: 1

Views: 474

Answers (2)

kendlete
kendlete

Reputation: 224

I think you can use an association proxy

class Blog(Base):

    comments = association_proxy('posts', 'comments')

Upvotes: 2

Zach Kelling
Zach Kelling

Reputation: 53839

You need to use join:

comments = session.query(Comment).join(Post).filter(Post.blog == b1).all()

Upvotes: 0

Related Questions