【问题标题】:What is the difference between with_entities and load_only in SQLAlchemy?SQLAlchemy 中的 with_entities 和 load_only 有什么区别?
【发布时间】:2018-04-21 21:23:11
【问题描述】:

查询我的数据库时,我只想加载指定的列。使用with_entities 创建查询需要引用模型列属性,而使用load_only 创建查询需要与列名对应的字符串。我更喜欢使用load_only,因为使用字符串创建动态查询更容易。两者有什么区别?

load_only documentation

with_entities documentation

【问题讨论】:

标签: python sqlalchemy


【解决方案1】:

有一些不同之处。丢弃不需要的列(如问题中所示)时最重要的一点是,使用 load_only 仍会导致创建对象(模型实例),而使用 with_entities 只会为您提供具有所选列值的元组。

>>> query = User.query
>>> query.options(load_only('email', 'id')).all()
[<User 1 using e-mail: n@d.com>, <User 2 using e-mail: n@d.org>]
>>> query.with_entities(User.email, User.id).all()
[('n@d.org', 1), ('n@d.com', 2)]  

load_only

load_only() 延迟从模型中加载特定列。 它从查询中删除 。稍后您仍然可以访问所有其他列,但在您尝试访问它们时会执行额外的查询(在后台)。

当您在数据库中存储诸如用户图片之类的内容时,“仅加载”很有用,但您不想在不需要时浪费时间传输图像。例如,当显示用户列表时,这可能就足够了:

User.query.options(load_only('name', 'fullname'))

with_entities

with_entities() 可以添加或删除(简单:替换)模型;你甚至可以用它来修改查询,用你自己的函数替换选定的实体,比如func.count()

query = User.query
count_query = query.with_entities(func.count(User.id)))
count = count_query.scalar()

请注意,生成的查询与 query.count() 不同,后者可能会更慢 - at least in MySQL(因为它会生成子查询)。

with_entities 的额外功能的另一个示例是:

query = (
    Page.query
    .filter(<a lot of page filters>)
    .join(Author).filter(<some author filters>)
)
pages = query.all()

# ok, I got the pages. Wait, what? I want the authors too!
# how to do it without generating the query again?

pages_and_authors = query.with_entities(Page, Author).all()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 2016-02-14
    • 2012-09-03
    • 2017-09-04
    • 2017-12-04
    • 2019-08-25
    • 2012-11-24
    • 2015-04-25
    相关资源
    最近更新 更多