SQLAlchemy load_only on parent model
<p>When eager loading a child relationship, how can I only load few columns of the parent model:</p>

<p>This works if I only need <code>title</code> column of the <code>chapters</code> model:</p>

<pre><code>session.query(Book)\
    .options(joinedload('chapters').load_only('title'))
</code></pre>

<p>But this throws an error:</p>

<pre><code>session.query(Book.author)\
    .options(joinedload('chapters').load_only('title'))
</code></pre>

<blockquote>
  <p>Query has only expression-based entities - can't find property named
  'chapters'.</p>
</blockquote>

<p>In other words I want this SQL in ORM syntax:</p>

<pre><code>SELECT 
    books.author,
    chapters.title,
FROM 
    books JOIN chapters ON book.id = chapters.book_id
</code></pre>

<p>The error message says you're only selecting <code>Book.author</code>, instead of instances of <code>Book</code>. Where is <code>chapters</code> going to go if all it's returning is a list of strings (for <code>author</code>).</p>

<p>You can either do:</p>

<pre><code>session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters)
</code></pre>

<p>or</p>

<pre><code>session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))
</code></pre>

python sql orm sqlalchemy