SQLAlchemy:分离对象的修改 [英] SQLAlchemy: Modification of detached object
问题描述
我想使用 orm 在 SQLAlchemy 中复制模型实例(行).我的第一个想法是这样做:
I want to duplicate a model instance (row) in SQLAlchemy using the orm. My first thought was to do this:
i = session.query(Model)
session.expunge(i)
old_id = i.id
i.id = None
session.add(i)
session.flush()
print i.id #New ID
然而,显然分离的对象仍然记住"它有什么 id,即使我在分离时将 id 设置为 None.因此, session.flush() 尝试执行 UPDATE 将主键更改为 null.
However, apparently the detached object still "remembers" what id it had, even though I set the id to None while it was detached. Thus, session.flush() tries to execute an UPDATE changing the primary key to null.
这是预期的行为吗?如何删除此属性的内存",并在将分离的对象重新添加到会话时将其视为新对象?一般来说,如何克隆 SQLAlchemy 模型实例?
Is this expected behavior? How can I remove the 'memory' of this attribute, and just treat the detached object as a new object upon re-adding it to the session? How, in general, does one clone an SQLAlchemy model instance?
推荐答案
此案例可使用 make_transient() 辅助函数:
this case is available using the make_transient() helper function:
inst = session.query(Model).first()
session.expunge(inst)
make_transient(inst)
inst.id = None
session.add(inst)
session.flush()
print inst.id #New ID
这篇关于SQLAlchemy:分离对象的修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!