python - SQLalchemy "load_only"不只加载指定的列

标签 python sqlalchemy

我正在尝试使用 sqlalchemy 的 load_only 函数从表中选择列的子集。不幸的是,它似乎并不只返回函数调用中指定的列——具体来说,它似乎还获取了主键(在我的例子中,是一个 auto_increment id 字段)。

一个简单的例子,如果我使用这个语句来构建一个查询,:

query = session.query(table).options(load_only('col_1', 'col_2'))

然后 query.statement 看起来像这样:

SELECT "table".id, "table"."col_1", "table"."col_2" 
FROM "table"

这不是我所期望的 - 鉴于我已经指定了要使用的“唯一”列... id 来自哪里 - 有没有办法删除它?

最佳答案

如果查询完整的 ORM 实体,推迟主键是没有意义的,因为 an entity must have an identity so that a unique row can be identified in the database table .因此,尽管您有 load_only(),但查询包括主键。如果您只需要数据,您应该专门查询:

session.query(table.col1, table.col2).all()

结果是键控元组,在许多情况下您可以像对待实体一样对待它们。

实际上有一个 issue where having load_only() did remove the primary key from the select list , 它是 fixed in 0.9.5 :

[orm] [bug] Modified the behavior of orm.load_only() such that primary key columns are always added to the list of columns to be “undeferred”; otherwise, the ORM can’t load the row’s identity. Apparently, one can defer the mapped primary keys and the ORM will fail, that hasn’t been changed. But as load_only is essentially saying “defer all but X”, it’s more critical that PK cols not be part of this deferral.

关于python - SQLalchemy "load_only"不只加载指定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54157389/

相关文章:

mysql - to_sql到mysql插入错误

python - 有条件地计算 pandas groupby 对象中的值

python - 如何让 list_blobs 表现得像 gsutil

python - SQLAlchemy:提交后对象映射丢失?

python - 如何在数据库中插入唯一数据/处理重复数据

python - 有什么理由不使用 SQLObject 而不是 SQLAlchemy?

python - 通过 Flask URL 传递对象

python - 将 Python Pandas DataFrame 写入 Word 文档

结合两个 FOR 循环和一个 IF 语句的 Pythonic 方法?

python - 使用 SQLAlchemy 进行 Pyramid 异常记录 - 命令未提交