如何以通用方式复制SQLAlchemy映射对象的关系?

时间:2015-05-16 01:56:49

标签: python sqlalchemy

我有复制SQLAlchmey数据对象的函数。它适用于所有类型的SQLA对象。这意味着它(从givin /现有实例)将数据成员(排除主键和唯一成员)复制到相同类型的新实例。

但问题是没有设置relationship()。正确复制外键的数值。但是没有设置真实外来数据对象的“指针”。

以下是演示的简化代码。 TrainingUnitDate._machine是我谈到的非集合成员。

import sqlalchemy as sa

def DuplicateObject(oldObj):
    """
    Create a duplicate of an SQLAlchemy mapped object and return it.

    It create a new instance and copy all mapped data members to it.
    It doesn't copy the primary key or unique data members.
    """
    mapper = sa.inspect(type(oldObj))
    newObj = type(oldObj)()

    for name, col in mapper.columns.items():
        if not col.primary_key and not col.unique:
            setattr(newObj, name, getattr(oldObj, name))

    return newObj


class MachineData(_Base):
    __tablename__ = 'Machine'

    _oid = sa.Column('oid', sa.Integer, primary_key=True)


class TrainingUnitData(_Base):
    __tablename__ = 'TrainingUnit'

    _oid = sa.Column('oid', sa.Integer, primary_key=True)
    _machine_fk = sa.Column('machine', sa.Integer, sa.ForeignKey('Machine.oid'))
    # THIS is the member its all about
    _machine = sao.relationship("MachineData")

0 个答案:

没有答案