sqlalchemy的merge使用

Posted 沧海一粟,何以久远

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlalchemy的merge使用相关的知识,希望对你有一定的参考价值。

1、先看下文档

merge(instanceload=True)

Copy the state of a given instance into a corresponding instance within this Session.

Session.merge() examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object from the database based on primary key, and if none can be located, creates a new instance. The state of each attribute on the source instance is then copied to the target instance. The resulting target instance is then returned by the method; the original source instance is left unmodified, and un-associated with the Session if not already.

This operation cascades to associated instances if the association is mapped with cascade="merge".

See Merging for a detailed discussion of merging.

Changed in version 1.1: - Session.merge() will now reconcile pending objects with overlapping primary keys in the same way as persistent. See Session.merge resolves pending conflicts the same as persistent for discussion.

Parameters:
  • instance – Instance to be merged.
  • load? –

    Boolean, when False, merge() switches into a “high performance” mode which causes it to forego emitting history events as well as all database access. This flag is used for cases such as transferring graphs of objects into a Session from a second level cache, or to transfer just-loaded objects into the Session owned by a worker thread or process without re-querying the database.

    The load=False use case adds the caveat that the given object has to be in a “clean” state, that is, has no pending changes to be flushed - even if the incoming object is detached from any Session. This is so that when the merge operation populates local attributes and cascades to related objects and collections, the values can be “stamped” onto the target object as is, without generating any history or attribute events, and without the need to reconcile the incoming data with any existing related objects or collections that might not be loaded. The resulting objects from load=False are always produced as “clean”, so it is only appropriate that the given objects should be “clean” as well, else this suggests a mis-use of the method.

2、简单说下,merge的作用是合并,查找primary key是否一致,一致则合并,不一致则新建

参考:

1、http://docs.sqlalchemy.org/en/latest/orm/session_api.html

以上是关于sqlalchemy的merge使用的主要内容,如果未能解决你的问题,请参考以下文章

honeysql merge-where 构建大型查询

Python代码阅读(第19篇):合并多个字典

使用sqlacodegen自动生成sqlalchemy的model代码

git在merge后会不会把最新代码更新过来

从 python 使用 TSQL(SQL Server 上的 mssql)时,如何为 SQLAlchemy 自动生成 ORM 代码?

SqlAlchemy - 按关系属性过滤