Har*_*wal 22 python sqlalchemy python-2.7 flask-sqlalchemy
我想克隆一个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)
Run Code Online (Sandbox Code Playgroud)
它只是更新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
Run Code Online (Sandbox Code Playgroud)
Tas*_*lou 26
这应该工作:
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)
Run Code Online (Sandbox Code Playgroud)
一种可能的方法是使用dictalchemy:
new_instance = InstanceModel(**old_instance.asdict())
Run Code Online (Sandbox Code Playgroud)
小智 6
此方法将克隆任何 sqlalchemy 数据库对象。将其添加到您的模型的类中。请注意,新对象的 id 将在提交期间创建(请参阅评论):
def clone(self):
d = dict(self.__dict__)
d.pop("id") # get rid of id
d.pop("_sa_instance_state") # get rid of SQLAlchemy special attr
copy = self.__class__(**d)
db.session.add(copy)
# db.session.commit() if you need the id immediately
return copy
Run Code Online (Sandbox Code Playgroud)
For sqlalchemy 1.3 I ended up using a helper function.
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
Run Code Online (Sandbox Code Playgroud)
With this function you can solve the above problem using:
product_obj = products.all()[0] # Get the product from somewhere.
cloned_product_obj = clone_model(product_obj, product_uid='something')
Run Code Online (Sandbox Code Playgroud)
Depending on your use-case you might want to remove the call to db.session.commit() from this function.
This answer is based on /sf/answers/962670971/ (How to get a model’s columns?) and How do I get the name of an SQLAlchemy object's primary key? (How do I get a model’s primary keys?).
| 归档时间: |
|
| 查看次数: |
11690 次 |
| 最近记录: |