r/learnpython•
fuzz3289

Migrating Data from SQLite3 to Postgresql with SQLAlchemy

Hey Everyone,

We're working on moving to a postgresql database so we can better scale our application but don't want to lose our sqlite3 stuff. The application is based on Flask/SQLAlchemy so we have those libraries to work with. I've seen dumps and stuff but I was wondering if something like this is possible:

postgre_session = create_postgre_sesh()
sqlite_session = create_sqlite_sesh()

obja_list = sqlite_session.query(models.ObjectA).all()
properties = class_mapper(models.ObjectA).iterate_properties()

for obja in obja_list:
    kwargs = {prop: getattr(obja, prop) for prop in properties}
    new_obja = models.ObjectA(**kwargs)
    postgre_session.add(new_obja) 

postgre_session.commit()   

I'm running into errors like "Object already bound to session 1", which I don't understand because I'm effectively constructing a new object using the values from a previous object so I dont understand why my second session isn't ok with it? Is this a common way of doing things?

I'm open to other suggestions as well, since this is a one time thing (move to postgre and done) it can be a little hacky.

Posted Aug 12, 2015, 4:59 PM UTC

197
Loading comments…