SQLAlchemy: Modification of detached object

后端 未结 2 1823
心在旅途
心在旅途 2020-12-24 08:32

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          


        
相关标签:
2条回答
  • 2020-12-24 09:03

    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
    
    0 讨论(0)
  • 2020-12-24 09:06
    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)
    
    0 讨论(0)
提交回复
热议问题