首页 > 解决方案 > 使用 Python SQLAlchemy ORM 限制对某些字段的急切加载

问题描述

我正在使用 Python SQLAlchemy 1.3 我想预先加载三个表的结果集,其中的关系是:

documents -- belongs to --> document_types
documents -- belongs to --> users

我想要一个内部连接,所以我从具有用户和文档类型的“文档”中获取所有记录。这是一个很大的结果集,我想在一个查询中预先加载我的所有数据。

我想我已经弄清楚了这样的基础知识:

res = (
            session.query(Document)
            .join(Document.document_type)
            .join(Document.user)
            .options(
                contains_eager(Document.document_type), 
                contains_eager(Document.user) )
            .all() ) 

但我不需要内存中所有三个表的每个字段。我怎样才能选择要预先加载的字段,或者这是不可能的?例如,“document_types”的描述字段可能包含大量文本,我不想加载该字段。谢谢!

标签: pythonsqlalchemy

解决方案


推荐阅读