Skip to main content
 首页 » 编程设计

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

2024年12月31日9pander-it

我正在尝试使用 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.