Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 855
Sam R. Avatar asked Sep 17 '16 23:09

Sam R.


1 Answers

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"))
like image 99
univerio Avatar answered Oct 06 '22 19:10

univerio