Sam R.
Sam R.

Reputation: 16450

SQLAlchemy load_only on parent model

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

Upvotes: 12

Views: 11732

Answers (1)

univerio
univerio

Reputation: 20518

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"))

Upvotes: 20

Related Questions