1. 安装migrate模块
pip install flask_migrate
2. 创建manage对象,并接管app和db对象
manager = Manager(app, db)
3. 将数据库迁移操作集成到script中
manager.add_command(‘db‘, MigrateCommand)
案例代码:
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‘]=‘mysql://root:[email protected]:3306/flask_01‘ manager = Manager(app) db = SQLAlchemy(app) migrate = Migrate(app, db) # 使用migrate集成到script manager.add_command(‘db‘, MigrateCommand) class Book(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=True) hero_set = db.relationship(‘Hero‘, backref=‘book‘, lazy=‘dynamic‘) class Hero(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=True) book_id = db.Column(db.Integer, db.ForeignKey(‘book.id‘)) @app.route(‘/‘) def index(): return ‘index‘ if __name__ == ‘__main__‘: manager.run()
使用shell脚本执行数据库迁移
1. 创建makemigrations文件夹,及其相关文件。
python 文件名 init
2. 创建数据库迁移文件
python 文件名 migrate
3. 执行迁移文件
python 文件名 upgrade
原文地址:https://www.cnblogs.com/chao666/p/12424885.html
时间: 2024-11-09 05:09:47