运行 Flask-Migrate 时保留数据库中的现有表 [英] Preserve existing tables in database when running Flask-Migrate

查看:17
本文介绍了运行 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆