Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

python - Preserve existing tables in database when running 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...