When eager loading a child relationship, how can I only load few columns of the parent model:
This works if I only need title
column of the chapters
model:
session.query(Book)\
.options(joinedload('chapters').load_only('title'))
But this throws an error:
session.query(Book.author)\
.options(joinedload('chapters').load_only('title'))
Query has only expression-based entities - can't find property named 'chapters'.
In other words I want this SQL in ORM syntax:
SELECT
books.author,
chapters.title,
FROM
books JOIN chapters ON book.id = chapters.book_id
The error message says you're only selecting Book.author
, instead of instances of Book
. Where is chapters
going to go if all it's returning is a list of strings (for author
).
You can either do:
session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters)
or
session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With