Skip to content Skip to sidebar Skip to footer

How To Use Make_transient() To Duplicate An Sqlalchemy Mapped Object?

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 interpreted

Solution 1:

After making a object instance transient you have to remove its object-id. Without an object-id you can add it again to the database which will generate 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()

Post a Comment for "How To Use Make_transient() To Duplicate An Sqlalchemy Mapped Object?"