惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google Online Security Blog
Google Online Security Blog
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
V
V2EX
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
F
Full Disclosure
Y
Y Combinator Blog
V
V2EX - 技术
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
SecWiki News
SecWiki News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
量子位
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
K
Kaspersky official blog
B
Blog
A
Arctic Wolf
Hacker News: Ask HN
Hacker News: Ask HN
L
LangChain Blog
T
Tor Project blog
P
Privacy & Cybersecurity Law Blog
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
D
Docker
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
The Last Watchdog
The Last Watchdog
S
Security Affairs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
Simon Willison's Weblog
Simon Willison's Weblog

博客园 - 全栈测试笔记

博文阅读密码验证 - 博客园 FastAPI系列(24):ORM操作之删除接口开发 单例模式管理模型客户端的几种实现方式 博文阅读密码验证 - 博客园 FastAPI系列(23):ORM操作之编辑接口开发 FastAPI系列(22):ORM之多对多查询记录 FastAPI系列(21):ORM之多对多添加记录 CC Switch配置模型 Claude Code安装 FastAPI系列(20):ORM添加表记录 FastAPI系列(19):ORM响应页面数据 博文阅读密码验证 - 博客园 FastAPI系列(17):ORM的迁移命令 FastAPI系列(16):ORM创建模型类 FastAPI系列(15):Jinja2模板语法之控制结构 FastAPI系列(14):Jinja2模板语法之过滤器 FastAPI系列(13):Jinja2模板介绍、模板语法之变量渲染 FastAPI系列(12):响应模型参数 【汇总】FastAPI系列教程
FastAPI系列(18):ORM查询操作
全栈测试笔记 · 2026-02-01 · via 博客园 - 全栈测试笔记

添加表数据

手动依次添加以下表数据:

clas

teacher

course,依赖teacher

student,依赖clas

student_course,多对多的表

 

main.py

import uvicorn
from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise

from test_orm.api.student import student_api
from test_orm.settings import TORTOISE_ORM

app = FastAPI()

app.include_router(student_api, prefix="/student", tags=["学生接口"])

# register_tortoise是注册函数,fastapi一旦运行,register_tortoise已经执行,通过传递进去的app对象,监听服务启动和终止事件
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
)

if __name__ == '__main__':
    uvicorn.run('main:app', host='127.0.0.1', port=8001, reload=True, workers=1)

补充:

# 该方法会在fastapi启动时触发,内部通过传递进去的app对象,监听服务启动和终止事件
# 当检测到启动事件时,会初始化Tortoise对象,如果generate_schemas为True则还会进行数据库迁移
# 当检测到终止事件时,会关闭连接
register_tortoise(
    app,
    config=TORTOISE_ORM,
    # generate_schemas=True,  # 如果数据库为空,则自动生成对应表单,生产环境不要开
    # add_exception_handlers=True,  # 生产环境不要开,会泄露调试信息
)

查询所有:all

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
def getAllStudent():
    # 查询所有 all方法
    students = Student.all()  # Queryset: [Student(),Student(),Student()]
    print(students)  # <tortoise.queryset.QuerySet object at 0x0000025B92F0FD00>

    return {"msg": "查询所有学生"}

浏览器请求后:因为没有加await,所以结果是一个QuerySet,加了才是返回对象

image

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
def getAllStudent():
    # 查询所有all方法
    students = Student.all()  # Queryset: [Student(),Student(),Student()]
    print(students)  # <tortoise.queryset.QuerySet object at 0x0000025B92F0FD00>
    for student in students:
        print(student.name, student.sno)
    return {"msg": "查询所有学生"}

浏览器请求后报错:tortoise.exceptions.ParamsError: QuerySet indices must be slices

image

tortoise是支持异步操作数据库的orm,必须异步,协程并发(支持大并发,请求来了放到一个请求队列),加async

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    # 查询所有all方法
    students = await Student.all()  # Queryset: [Student(),Student(),Student()]
    print(students)
    for student in students:
        print(student.name, student.sno)
    return {"msg": "查询所有学生"}

浏览器请求后

image

可以循环,也可以索引访问

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    # (1) 查询所有 all方法
    students = await Student.all()  # Queryset: [Student(),Student(),Student()]
    print(students, type(students))

    for student in students:
        print(student.name, student.sno)

    print(students[0])
    print(students[1])
    print(students[0].name)
    return {"msg": "查询所有学生"}

浏览器请求后

image

过滤查询:filter

返回模型类型对象list

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    students = await Student.filter(name="ren")
    print(students, type(students))
    print(students[0].name)
    students = await Student.filter(clas_id=2)
    print(students)
    print(students[0].name)
    return {"msg": "ok"}

浏览器请求后

image

过滤查询:get

返回模型类型对象

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    students = await Student.get(name="ren")
    print(students, type(students))
    print(students.name)
    students = await Student.get(clas_id=2)
    print(students)
    print(students.name)
    return {"msg": "ok"}

浏览器请求后

image

模糊查询

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    students = await Student.filter(sno__gt=1001)  # __gt表示大于
    print(students, students[0], students[0].name)

    students = await Student.filter(sno__range=[1000, 9999])  # __range表示范围
    print(students, students[0], students[0].name)

    students = await Student.filter(sno__in=[1001, 2002])  # __in表示在哪些值中
    print(students, students[0], students[0].name)

    return {"msg": "ok"}

浏览器请求后

image

values查询

from fastapi import APIRouter

from test_orm.models import Student

student_api = APIRouter()


@student_api.get("/")
async def getAllStudent():
    students = await Student.filter(sno__range=[1, 10000])  # [Student(),Student(),Student(),...]
    print(students, students[0], students[0].name)
    students = await Student.all().values("name", "sno")  # [{},{},{},...]
    print(students, type(students))

    return {"结果": students}

浏览器请求后

image

接口文档请求

image

 如果是返回students

说明json数组也是json

image