FastAPI 使用 Tortoise-ORM 迁移数据库结构的详细步骤
FastAPI 中使用 Tortoise-ORM 迁移数据库结构
本教程将详细介绍如何在 FastAPI 项目中使用 Tortoise-ORM 和 Alembic 迁移数据库结构。
1. 安装依赖
首先,需要安装 Tortoise-ORM 和 Alembic:
pip install tortoise-orm alembic
2. 创建 Alembic 配置文件
在项目根目录下创建 alembic.ini 文件,内容如下:
[alembic]
script_location = alembic
sqlalchemy.url = sqlite:///test.db
script_location:迁移脚本存储位置。sqlalchemy.url:数据库连接地址。
3. 初始化 Alembic
使用以下命令初始化 Alembic:
alembic init alembic
这将在项目根目录下创建一个名为 alembic 的文件夹,里面包含迁移脚本的相关文件。
4. 创建数据模型
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)
5. 创建迁移脚本
使用以下命令生成迁移脚本:
alembic revision --autogenerate -m 'create users table'
这将在 alembic/versions 目录下生成一个迁移脚本文件,文件名为自动生成的一串数字。
6. 执行迁移脚本
使用以下命令执行迁移脚本:
alembic upgrade head
这将在数据库中创建对应的表。
7. 修改数据模型并生成新的迁移脚本
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'
8. 执行新的迁移脚本
使用以下命令执行新的迁移脚本:
alembic upgrade head
这将在数据库中更新对应的表结构。
总结
以上步骤介绍了如何使用 Tortoise-ORM 和 Alembic 在 FastAPI 项目中迁移数据库结构。通过创建数据模型、生成迁移脚本和执行迁移,可以方便地管理数据库的演变。
原文地址: https://www.cveoy.top/t/topic/nApK 著作权归作者所有。请勿转载和采集!