Using flask-migrate

1 Introduction

# Tables and fields change, there will be records, and they will be automatically synchronized to the database--"django supports this operation
# Native sqlalchemy does not support modifying tables
# flask-migrate can implement
    python manage.py makemigrations similar to django # Record
    python manage.py migrate #real synchronization to the database

2. Preparation -

 Install flask, flask-script, flask-migrate, flask and flask-migrate do not install the latest, there will be version conflicts

pip insatll flask==2.2.2
pip install flask-script==2.0.3
pip install flask-migrate==2.7.0

2.1 In manage.py, that is, the app.py of the newly created project

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
manager = Manager(app)
# flask-script可以自定义命令---》
# flask-migrate本质是它借助于flask-script增加了几个命令来对数据库表和字段进行管理
Migrate(app, db) # sqlalchemy的db对象
manager.add_command('db', MigrateCommand) 
        
manager.run() # 以后使用python manage.py runserver 启动项目

 2.2 very important

Also import the created table name on the __init__ page of apps

from .user.models import User

 2.3 Execute it for the first time in the future

python manage.py db init  
# 生成一个migrations文件夹,里面以后不要动,记录迁移的编号

2.4 After 4, write tables in models.py, add fields, delete fields, and change parameters

 5 只需要执行
    	python manage.py db migrate  # 记录
        python manage.py db upgrade  # 真正的同步进去

Guess you like

Origin blog.csdn.net/xiaolisolovely/article/details/132215203