fastapi中使用tortoise-orm 数据库结构如何迁移
- 安装tortoise-orm和alembic
pip install tortoise-orm alembic
- 在项目根目录下创建alembic.ini文件
[alembic]
script_location = alembic
sqlalchemy.url = sqlite:///test.db
其中,script_location是迁移脚本存储位置,sqlalchemy.url是数据库连接地址。
- 使用alembic初始化迁移脚本
alembic init alembic
会在项目根目录下创建一个名为alembic的文件夹,里面包含迁移脚本的相关文件。
- 创建数据模型
from tortoise import fields
from tortoise.models import Model
class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=20)
age = fields.IntField()
created_at = fields.DatetimeField(auto_now_add=True)
- 创建迁移脚本
alembic revision --autogenerate -m "create users table"
会在alembic/versions目录下生成一个迁移脚本文件,文件名为自动生成的一串数字。
- 执行迁移脚本
alembic upgrade head
会在数据库中创建对应的表。
- 修改数据模型并生成新的迁移脚本
class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=20)
age = fields.IntField()
email = fields.CharField(max_length=50)
created_at = fields.DatetimeField(auto_now_add=True)
alembic revision --autogenerate -m "add email column to users table"
- 执行新的迁移脚本
alembic upgrade head
会在数据库中更新对应的表结构
原文地址: https://www.cveoy.top/t/topic/cRbO 著作权归作者所有。请勿转载和采集!