如何使用新的主键克隆sqlalchemy数据库对象 [英] How to clone a sqlalchemy db object with new primary key

查看:62
本文介绍了如何使用新的主键克隆sqlalchemy数据库对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想克隆一个sqlalchemy对象:

I want to clone a sqlalchemy object:

我尝试过

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

it is just updating the old_object only

这是products.save函数的代码

here is the code of products.save function

class Service(object):

        __model__ = None

       def save(self, model):
            self._isinstance(model)
            db.session.add(model)
            db.session.commit()
            return model

推荐答案

这应该有效:

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)

这篇关于如何使用新的主键克隆sqlalchemy数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆