Reputation: 51
I have a flask app which is using Flask-SQLAlchemy to access mysql. Now I want to refactor the data model in same app, so I created a new version model file but a few of tables should have same name with old table.
oldmodel.py
class TableA(db.Model):
__tablename__ = 'TableA'
...
newmodel.py
class TableA(db.Model):
__tablename__ = 'TableA'
...
I write a function, the idea is to query data by old MetaData then write to new database by new MetaData after some column data manipulation, but it obviously will report same table name conflict in Flask-SQLAlchemy. the error message is
sqlalchemy.exc.InvalidRequestError: Table 'TableA' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
I don't want to use Flask-migrate on old database, but to create new database.
I also tried __bind_key__
, it seems working in a new table but not working in exist table which already had data.
is it possible to avoid this to use two version of DataModel in same app? or other approach?
Upvotes: 2
Views: 898
Reputation: 51
finally, I found a way to do that, changed the Model to pure sqlalchemy style, like
oldmodel.py
from sqlalchemy.ext.declarative import declarative_base
BaseOld = declarative_base()
class TableA(BaseOld):
__tablename__ = 'TableA'
newmodel.py
from sqlalchemy.ext.declarative import declarative_base
BaseNew = declarative_base()
class TableA(BaseNew):
__tablename__ = 'TableA'
then create two engines to different db with corresponding session. now it is very easy to query from old db and write to new db as you want. one trick when import same name class is using 'from XXX import XXX as XXX' to avoid class name conflict.
another way if still use db.Model of flask-sqlalchemy is to use bind_key feature. it can split Model class to different database, but one big limitation is the Model Class Name should not conflict.
Upvotes: 2