如何使用make_transient()复制SQLAlchemy映射对象?

时间:2015-05-17 12:51:05

标签: python sqlalchemy

我知道很多次问过如何复制或复制SQLAlchemy映射对象的问题。答案总是取决于需求或如何解释“复制”或“复制”。 这是该问题的专门版本,因为我得到了使用make_transient()的提示。

但我有一些问题。我真的不知道如何处理主键(PK)。在我的用例中,PK总是由SQLA(或后台的DB)自动生成。但是,对于新的重复对象,这不会发生。

代码有点伪。

import sqlalchemy as sa
from sqlalchemy.orm.session import make_transient

_engine = sa.create_engine('postgres://...')
_session = sao.sessionmaker(bind=_engine)()


class MachineData(_Base):
    __tablename__ = 'Machine'    
    _oid = sa.Column('oid', sa.Integer, primary_key=True)


class TUnitData(_Base):
    __tablename__ = 'TUnit'
    _oid = sa.Column('oid', sa.Integer, primary_key=True)
    _machine_fk = sa.Column('machine', sa.Integer, sa.ForeignKey('Machine.oid'))
    _machine = sao.relationship("MachineData")

    def __str__(self):
        return '{}.{}: oid={}(hasIdentity={}) machine={}(fk={})' \
        .format(type(self), id(self),
                self._oid, has_identity(self),
                self._machine, self._machine_fk)


if __name__ == '__main__':
    # any query resulting in one persistent object
    obj = GetOneMachineDataFromDatabase()

    # there is a valid 'oid', has_identity == True
    print(obj)

    # should i call expunge() first?

    # remove the association with any session
    # and remove its “identity key”
    make_transient(obj)

    # 'oid' is still there but has_identity == False
    print(obj)

    # THIS causes an error because the 'oid' still exsits
    # and is not new auto-generated (what should happen in my
    # understandings)
    _session.add(obj)
    _session.commit()

1 个答案:

答案 0 :(得分:5)

if __name__ == '__main__':
    obj = GetOneMachineDataFromDatabase()

    make_transient(obj)
    obj._oid = None
    _session.add(obj)
    # this include a flush() and create a new primary key
    _session.commit()