父模型上的SQLAlchemy load_only [英] SQLAlchemy load_only on parent model
本文介绍了父模型上的SQLAlchemy load_only的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当渴望加载子关系时,如何只加载父模型的几列:
When eager loading a child relationship, how can I only load few columns of the parent model:
如果我只需要chapters
模型的title
列,则此方法有效:
This works if I only need title
column of the chapters
model:
session.query(Book)\
.options(joinedload('chapters').load_only('title'))
但这会引发错误:
session.query(Book.author)\
.options(joinedload('chapters').load_only('title'))
查询仅具有基于表达式的实体-找不到名为 '章节'.
Query has only expression-based entities - can't find property named 'chapters'.
换句话说,我想要使用ORM语法的此SQL:
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
推荐答案
错误消息指出您仅选择Book.author
,而不是Book
的实例.如果chapters
返回的只是字符串列表(对于author
),该去哪里?
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
).
您可以执行以下操作:
session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters)
或
session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))
这篇关于父模型上的SQLAlchemy load_only的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文