我想克隆一个sqlalchemy对象:
我试过
product_obj = products.all()[0] #here products is service name
product_obj.product_uid = 'soemthing' #here product_uid is the pk of product model
products.save(product_obj)
它只是更新old_object
这是products.save函数的代码
class Service(object):
__model__ = None
def save(self, model):
self._isinstance(model)
db.session.add(model)
db.session.commit()
return model
答案 0 :(得分:22)
这应该有效:
product_obj = products.all()[0]
db.session.expunge(product_obj) # expunge the object from session
make_transient(product_obj) # http://docs.sqlalchemy.org/en/rel_1_1/orm/session_api.html#sqlalchemy.orm.session.make_transient
product_obj.product_uid = 'something'
db.session.add(product_obj)
答案 1 :(得分:3)
一种可能的方法是使用dictalchemy:
new_instance = InstanceModel(**old_instance.asdict())
答案 2 :(得分:2)
对于sqlalchemy 1.3,我最终使用了一个辅助函数。
def clone_model(model, **kwargs):
"""Clone an arbitrary sqlalchemy model object without its primary key values."""
# Ensure the model’s data is loaded before copying.
model.id
table = model.__table__
non_pk_columns = [k for k in table.columns.keys() if k not in table.primary_key]
data = {c: getattr(model, c) for c in non_pk_columns}
data.update(kwargs)
clone = model.__class__(**data)
db.session.add(clone)
db.session.commit()
return clone
使用此功能,您可以使用以下方法解决上述问题:
product_obj = products.all()[0] # Get the product from somewhere.
cloned_product_obj = clone_model(product_obj, product_uid='something')
根据您的用例,您可能希望从此函数中删除对db.session.commit()
的调用。
此答案基于https://stackoverflow.com/a/13752442/769486(如何获取模型的列?)和How do I get the name of an SQLAlchemy object's primary key?(如何获取模型的主键?)。