运行Flask-Migrate时保留数据库中的现有表 [英] Preserve existing tables in database when running Flask-Migrate
问题描述
我有一个包含现有表的数据库.我的代码具有 User
模型.我使用Flask-Migrate生成了一个修订版本并运行它,并且它在创建用户表时删除了我现有的表.如何在不删除现有表的情况下运行迁移?
I have a database with existing tables. My code has a User
model. I generated a revision using Flask-Migrate and ran it, and it deleted my existing tables while creating the user table. How can I run migrations without removing the existing tables?
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'my_data'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
if __name__ == '__main__':
manager.run()
推荐答案
如果数据库中已有表,并且代码中没有相应的模型,则Alembic(Flask-Migrate)仅知道存在数据库和代码之间的差异.(默认情况下)它不知道您要保留这些表不变.
If you have existing tables in your database, and they don't have a corresponding model in your code, Alembic (Flask-Migrate) only knows that there is a difference between your database and your code. It can't know (by default) that you meant to leave those tables untouched.
传递 include_object
函数对环境产生影响,以影响Alembic将为其生成命令的数据库对象.下面的示例跳过列出的表名,但允许其他所有内容.
Pass an include_object
function to the environment to effect what database objects Alembic will generate commands for. The following example skips the listed table names, but allows everything else.
def include_object(object, name, type_, reflected, compare_to):
if type_ == 'table' and name in ('table', 'names', 'to', 'skip'):
return False
return True
# in env.py
context.configure(
# ...
include_object=include_object
)
这篇关于运行Flask-Migrate时保留数据库中的现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!