我想复制(复制)一个由 SQLAlchemy 映射的对象。它应该只复制我创建的数据,而不是所有底层的东西。它不应复制主键或唯一值。
这在创建与上一个只有一点点不同的新数据条目时很有用。因此用户不必再次输入所有数据。
一个重要的要求是,当表中的列名(例如name
)和成员名称(例如_name
)时,这需要起作用>) 在 python 类中是不一样的。
此(简化的)代码适用于所有 declarative_base() 派生类,但仅当 col-name 和 member-name 相同时才有效。
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 是如何知道这个连接的?我该如何照顾它?
最佳答案
import sqlalchemy as sqa
def duplicate_object(old_obj):
# SQLAlchemy related data class?
if not isinstance(old_obj, _Base):
raise TypeError('The given parameter with type {} is not '
'mapped by SQLAlchemy.'.format(type(old_obj)))
mapper = sa.inspect(type(old_obj))
new_obj = type(old_obj)()
for name, col in mapper.columns.items():
# no PrimaryKey not Unique
if not col.primary_key and not col.unique:
setattr(new_obj, name, getattr(old_obj, name))
return new_obj
看起来这项工作。即使成员以双下划线 (__name
) 开头。
但是 SQLA-mailinglist 上有人mentioned
It’s not a generalized solution for the whole world, though. It doesn’t take into account columns that are part of unique Index objects or columns that are mentioned in standalone UniqueConstraint objects.
但是因为 SQLA-docu(对我来说!)很难阅读和理解,所以我不太确定代码中发生了什么——尤其是在 for
结构中。 items()
背后是什么,为什么会有两个参数(name
, col
)?
关于python - 如何以正确的方式复制 SQLAlchemy 映射的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29039635/