How to clone a sqlalchemy db object with new primary key

Harshit Agarwal picture Harshit Agarwal · Mar 5, 2015 · Viewed 17.4k times · Source

I want to clone a sqlalchemy object:

I tried it by

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)

it is just updating the old_object only

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

Answer

Tasos Vogiatzoglou picture Tasos Vogiatzoglou · Mar 5, 2015

This should work:

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)