ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

FastAPI系列(16):ORM创建模型类

FastAPI系列(16):ORM创建模型类

 

本系列汇总,请查看这里:https://www.cnblogs.com/uncleyong/p/19503695 

Tortoise ORM简介

官网:https://tortoise.org.cn/

源代码:https://github.com/tortoise/tortoise-orm/

Tortoise ORM 是一款为 Python 异步编程(Asyncio)设计的 ORM(对象关系映射)工具,它的设计灵感来自 Django ORM,语法风格也和 Django ORM 非常相似,但完全适配异步场景(比如 FastAPI、Starlette 等异步 Web 框架),可以让你用面向对象的方式操作数据库,无需直接编写 SQL 语句。

简单来说:
  • 核心特点:纯异步、支持多种数据库(PostgreSQL、MySQL、SQLite)、语法接近 Django ORM(学习成本低)、支持迁移(migrations)、类型提示友好。
  • 适用场景:异步 Python 项目(如 FastAPI 接口开发),替代同步 ORM(如 SQLAlchemy 同步版、Django ORM)。

安装

参考:https://tortoise.org.cn/getting_started.html

安装 tortoise:pip install tortoise-orm

您还可以使用您的数据库驱动程序进行安装,对于 MySQL:pip install tortoise-orm[asyncmy]

参考:GitHub - tortoise/tortoise-orm: Familiar asyncio ORM for python, built with relations in mind

image

 

创建模型类

1.主表

  • Student:学生表
  • Course:课程表
  • Clas:班级表
  • Teacher:教师表

2. 关联表

  • Student_course:学生与课程的多对多关系表

 

目录结构

image

 

models.py
# 选课
from tortoise import fields
from tortoise.models import Modelclass Student(Model):id = fields.IntField(pk=True, description="主键")name = fields.CharField(max_length=32, description="姓名")pwd = fields.CharField(max_length=32, description="密码")sno = fields.IntField(description="学号")# 一对多的关系clas = fields.ForeignKeyField("models.Clas", related_name="students")  # 最后数据库中字段是clas_id,如果这里我们直接写成clas_id,最后数据库中是clas_id_id# 多对多的关系courses = fields.ManyToManyField("models.Course", related_name="students", description='学生选课表')  # 生成的表名是student_course,字段是student_id、course_idclass Course(Model):id = fields.IntField(pk=True)name = fields.CharField(max_length=32, description="课程名称")teacher = fields.ForeignKeyField("models.Teacher", related_name='courses', description='课程讲师表')# addr = fields.CharField(max_length=32, description="教室", default="")# desc = fields.CharField(max_length=32, description="教室信息", default="")class Clas(Model):id = fields.IntField(pk=True)name = fields.CharField(max_length=32, description="班级名称")class Teacher(Model):id = fields.IntField(pk=True)name = fields.CharField(max_length=32, description="姓名")pwd = fields.CharField(max_length=32, description="密码")tno = fields.IntField(description="老师编号")

 

 
返回列表