2021年1月7日星期四

How to bulk load relations in sqlalchemy for a subset of parents?

Let's say I have two models Blog and Comment with a one to many relationship.

class Blog(Base):      id = Column(Integer, primary_key=True)      comments = relationship("Comment")    class Comment(Base):      id = Column(Integer, primary_key=True)      blog = relationship("Blog")  

I can efficiently query blogs along with their comments with a subquery like so

session.query(Blog).filter(...filter_criteria...).options(subqueryload(Blog.comments)).all()    

This emits two separate queries - one to load blogs and another to load comments.

How do I load comments if I already have a bunch of blog objects already queried? The reason I can't use subqueryload while fetching blogs is there is application logic that uses a subset blogs whose comments are required.

In other words, if I have 5 blog objects in a list, is there a way to load comments efficiently so I can access them this way:

blogs = [b1, b2, b3, b4, b5]  # Do something here to efficiently load comments  for blog in blogs:      blog.comments  
https://stackoverflow.com/questions/65609101/how-to-bulk-load-relations-in-sqlalchemy-for-a-subset-of-parents January 07, 2021 at 04:41PM

没有评论:

发表评论