SQLAlchemy:修改分离的对象 [英] SQLAlchemy: Modification of detached object

查看:149
本文介绍了SQLAlchemy:修改分离的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用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,即使我设置当它被分离时,该标识为无。因此,session.flush()尝试执行更改主键为null的UPDATE。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆