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:
if not col.primary_key and not col.unique:
setattr(newObj, col.key, getattr(oldObj, col.key))
return newObj
col.key - . python , . , SQLAlchemy -. SQLA ? ?
user4183320