I have the following scenario:
class Author(Base):
__tablename__ = \'author\'
id = Column(Integer, primary_key = True)
name = Column(String)
bo
In short, this is not possible. (If it were, an Author
instance would have different books
attribute depending on how it was queried, which doesn't make sense.)
What you could do instead is query the reverse relationship:
books = session.query(Book) \
.filter(Book.title.like('%SQL%')) \
.all()
Then you can access .author
on each book to collect books written by the same author together.
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.