2016-09-17 54 views
2

當預先加載一個孩子的關係,我怎麼能只加載父模型的幾列:SQLAlchemy的LOAD_ONLY對父模型

這工作,如果我只需要chapters模式title列:

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:

SELECT 
    books.author, 
    chapters.title, 
FROM 
    books JOIN chapters ON book.id = chapters.book_id 

回答

3

該錯誤消息說,你只是選擇Book.author,而不是Book實例。如果chapters全部返回的是字符串列表(對於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")) 
+0

非常感謝你。 – norbertpy