gpt4 book ai didi

python - SQLAlchemy 不仅通过主键从身份映射中获取项目

转载 作者:太空狗 更新时间:2023-10-30 02:58:27 24 4
gpt4 key购买 nike

是否可以使用不是来自主键的几个字段来从身份映射中检索项目(之前已经获取)?例如,我经常通过(external_id, platform_id)对来查询一个表,它是唯一键,但不是主键。在这种情况下,我想省略不必要的 SQL 查询。

最佳答案

identity_map 和 get() 的简要概述:

标识映射在 SQLAlchemy 的session 对象的生命周期内保留,即在网络服务或 RESTful api 的情况下,session 对象的生命周期不超过单个请求(推荐)。

发件人:http://martinfowler.com/eaaCatalog/identityMap.html

An Identity Map keeps a record of all objects that have been read from the database in a single business transaction. Whenever you want an object, you check the Identity Map first to see if you already have it.

在 SQLAlchemy 的 ORM 中有一个特殊的查询方法 get(),它首先使用 pk(唯一允许的参数)查找 identity_map 并从身份映射返回对象,实际执行 SQL 查询并访问数据库。

来自docs :

get(ident)

Return an instance based on the given primary key identifier, or None if not found.

get() is special in that it provides direct access to the identity map of the owning Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.


只有 get() 使用 identity_map - official docs :

It’s somewhat used as a cache, in that it implements the identity map pattern, and stores objects keyed to their primary key. However, it doesn’t do any kind of query caching. This means, if you say session.query(Foo).filter_by(name='bar'), even if Foo(name='bar') is right there, in the identity map, the session has no idea about that. It has to issue SQL to the database, get the rows back, and then when it sees the primary key in the row, then it can look in the local identity map and see that the object is already there. It’s only when you say query.get({some primary key}) that the Session doesn’t have to issue a query.


P.S. 如果您不使用 pk 进行查询,您首先就不会访问 identity_map


很少有相关的 SO 问题,有助于理清概念:

Forcing a sqlalchemy ORM get() outside identity map

关于python - SQLAlchemy 不仅通过主键从身份映射中获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33958770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com