How to use make_transient() to duplicate an SQLAlchemy mapped object?

后端 未结 1 748
时光说笑
时光说笑 2021-01-05 03:38

I know the question how to duplicate or copy a SQLAlchemy mapped object was asked a lot of times. The answer always depends on the needs or how \"duplicate\" or \"copy\" is

相关标签:
1条回答
  • 2021-01-05 04:24

    After makeing a object instance transient you have to remove its object-id. Without an object-id you can add it again to the database which generates a new object-id for it.

    if __name__ == '__main__':
        # the persistent object with an identiy in the database
        obj = GetOneMachineDataFromDatabase()
    
        # make it transient
        make_transient(obj)
        # remove the identiy / object-id
        obj._oid = None
        # adding the object again generates a new identiy / object-id
        _session.add(obj)
        # this include a flush() and create a new primary key
        _session.commit()
    
    0 讨论(0)
提交回复
热议问题