SQLAlchemy: Modification of detached object

余生颓废 提交于 2019-12-18 10:35:57

问题


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

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.

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?


回答1:


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



回答2:


def duplicate(self):
    arguments = dict()
    for name, column in self.__mapper__.columns.items():
        if not (column.primary_key or column.unique):
            arguments[name] = getattr(self, name)
    return self.__class__(**arguments)


来源:https://stackoverflow.com/questions/14636192/sqlalchemy-modification-of-detached-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!