Filtering relationships in SQL Alchemy

前端 未结 2 1898
刺人心
刺人心 2020-11-29 12:07

I have the following scenario:

class Author(Base):
  __tablename__ = \'author\'

  id    = Column(Integer, primary_key = True)
  name  = Column(String)

  bo         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 12:36

    Please read Routing Explicit Joins/Statements into Eagerly Loaded Collections. Then using contains_eager you can structure your query and get exactly what you want:

    authors = (
            session.query(Author)
            .join(Author.books)
            .options(contains_eager(Author.books)) # tell SA that we load "all" books for Authors
            .filter(Book.title.like('%SQL%'))
        ).all()
    

    Please note that you are actually tricking sqlalchemy into thinking that it has loaded all the collection of Author.books, and as such your session will know false information about the real state of the world.

提交回复
热议问题