How to duplicate an object with SQLAlchemy mapping correctly?

I want to duplicate (copy) an object mapped to SQLAlchemy. It should copy only the data that I created, and not all the materials that underlie. It should not copy primary keys or unique values.

This is useful when creating new data records that are slightly different from the last. Thus, the user does not need to enter all the data again.

Important requirement lies in the fact that it is necessary for work when the column name in the table (for example name) and the memeber name (for example _name) in the python class do not match.

This (simplified) code works for all declarative_base () classes, but ONLY when col-name and member name are the same.

import sqlalchemy as sa

def DuplicateObject(oldObj):
    mapper = sa.inspect(type(oldObj))
    newObj = type(oldObj)()

    for col in mapper.columns:
        # no PrimaryKey not Unique
        if not col.primary_key and not col.unique:
            setattr(newObj, col.key, getattr(oldObj, col.key))

    return newObj

col.key - . python , . , SQLAlchemy -. SQLA ? ?

+4
1
import sqlalchemy as sqa

def DuplicateObject(oldObj):
    # SQLAlchemy related data class?
    if not isinstance(oldObj, _Base):
        raise TypeError('The given parameter with type {} is not ' \
            'mapped by SQLAlchemy.'.format(type(oldObj)))

    mapper = sa.inspect(type(oldObj))
    newObj = type(oldObj)()

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

    return newObj

, . (__name).

- SQLA-mailinglist

. , , UniqueConstraint.

SQLA-document ( !) , , , for -construct. items() (name, col)?

0

All Articles