flask-sqlalchemy use of drop_all and create_all for specific tables

若如初见. 提交于 2020-01-01 05:12:26

问题


In sqlalchemy (0.8.2), drop_all() and create_all() both have a tables parameter, which can be a list of Table objects to drop or add.

In flask-sqlalchemy (1.0) these methods do not have this parameter.

What is the appropriate way to drop / create a subset of database tables, using flask-alchemy?


回答1:


Flask-SQLAlchemy's create_all() method will use the Base's metadata to create the table, by calling SQLAlchemy's MetaData.create_all() method. This method allows for a list of table objects to specify. You will also need to provide it a "bind", which is basically the engine. You can retrieve that using the engine property of Flask-SQLAlchemy.

So, you should be able to do...

db = SQLAlchemy(app)

class MyTable(db.Model):
    ...

class MyOtherTable(db.Model):
    ...

db.metadata.create_all(db.engine, tables=[
    MyTable.__table__,
    ...
])

This assumes that you are using a single database. Otherwise you would need to do a create_all() call for each database using get_engine().



来源:https://stackoverflow.com/questions/19232126/flask-sqlalchemy-use-of-drop-all-and-create-all-for-specific-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!