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

推荐订阅源

F
Fortinet All Blogs
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
WordPress大学
WordPress大学
Jina AI
Jina AI
GbyAI
GbyAI
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
腾讯CDC
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
Google DeepMind News
Google DeepMind News
月光博客
月光博客
博客园 - Franky
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
雷峰网
雷峰网
小众软件
小众软件
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 全栈测试笔记

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

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

说明

多对多,需要单独添加、更新

修改前

student表

image

student_course表没有ren的记录

全字段修改:方法一

from typing import List
from fastapi import APIRouter
from pydantic import BaseModel, field_validator
from test_orm.models import Student, Course

student_api = APIRouter()


class StudentIn(BaseModel):
    name: str
    pwd: str
    sno: int
    clas_id: int
    courses: List[int] = []

    @field_validator("name")
    def name_must_alpha(cls, value):  # 使用 cls 而不是 self
        assert value.isalpha(), 'name must be alpha'
        return value

    @field_validator("sno")
    @classmethod  # 必须在下面
    def sno_validate(cls, value):
        assert 1000 <= value < 10000, '学号要在[1000-10000)的范围内'
        return value


@student_api.put("/{student_id}")
async def updateStudent(student_id: int, student_in: StudentIn):
    # 和添加类似,多对多关系要单独处理
    print(student_in, type(student_in))
    await Student.filter(id=student_id).update(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno,
                                               clas_id=student_in.clas_id)
    #  设置多对多的选修课
    edit_stu = await Student.get(id=student_id)
    choose_courses = await Course.filter(id__in=student_in.courses)
    await edit_stu.courses.clear()  # 清除之前的关系
    await edit_stu.courses.add(*choose_courses)  # 重新绑定数据


    return edit_stu

请求数据

image

响应结果

image

image

数据库结果

image

image

全字段修改:方法二

from typing import List

from fastapi import APIRouter
from pydantic import BaseModel, field_validator

from test_orm.models import Student, Course

student_api = APIRouter()


@student_api.get("/{student_id}")
async def getOneStudent(student_id: int):
    student = await Student.get(id=student_id)

    return student



class StudentIn(BaseModel):
    name: str
    pwd: str
    sno: int
    clas_id: int
    courses: List[int] = []

    @field_validator("name")
    def name_must_alpha(cls, value):  # 使用 cls 而不是 self
        assert value.isalpha(), 'name must be alpha'
        return value

    @field_validator("sno")
    @classmethod  # 必须在下面
    def sno_validate(cls, value):
        assert 1000 <= value < 10000, '学号要在[1000-10000)的范围内'
        return value


@student_api.put("/{student_id}")
async def updateStudent(student_id: int, student_in: StudentIn):
    # 和添加类似,多对多关系要单独处理
    # print(student_in, type(student_in))
    # await Student.filter(id=student_id).update(name=student_in.name, pwd=student_in.pwd, sno=student_in.sno,
    #                                            clas_id=student_in.clas_id)
    #  设置多对多的选修课
    # edit_stu = await Student.get(id=student_id)
    # choose_courses = await Course.filter(id__in=student_in.courses)
    # await edit_stu.courses.clear()  # 清除之前的关系
    # await edit_stu.courses.add(*choose_courses)  # 重新绑定数据

    # 和上面等价,且更简单
    data = student_in.dict()
    print(data, type(data))
    courses = data.pop("courses")  # courses的值是course这个key对应的value;data中就没有courses这个key了;
    print(courses, type(courses))
    print(data, type(data))
    await Student.filter(id=student_id).update(**data)

    # 设置多对多的选修课
    edit_stu = await Student.get(id=student_id)
    choose_courses = await Course.filter(id__in=courses)
    await edit_stu.courses.clear()  # 清除之前的关系
    await edit_stu.courses.add(*choose_courses)  # 重新添加数据

    return edit_stu

请求数据

image

响应结果

image

image

数据库结果

image

image

部分字段修改

from typing import List

from fastapi import APIRouter
from pydantic import BaseModel, field_validator

from test_orm.models import Student, Course

student_api = APIRouter()


@student_api.get("/{student_id}")
async def getOneStudent(student_id: int):
    student = await Student.get(id=student_id)

    return student



class StudentIn(BaseModel):
    name: str
    pwd: str
    sno: int
    clas_id: int
    courses: List[int] = []

    @field_validator("name")
    def name_must_alpha(cls, value):  # 使用 cls 而不是 self
        assert value.isalpha(), 'name must be alpha'
        return value

    @field_validator("sno")
    @classmethod  # 必须在下面
    def sno_validate(cls, value):
        assert 1000 <= value < 10000, '学号要在[1000-10000)的范围内'
        return value


@student_api.put("/{student_id}")
async def updateStudent(student_id: int, student_in: StudentIn):
    # 只更新姓名和学号
    await Student.filter(id=student_id).update(
        name=student_in.name,
        sno=student_in.sno
    )

    # 获取更新后的学生信息返回
    updated_student = await Student.get(id=student_id)
    return updated_student

请求数据:只填需要修改的name和sno,其它默认不变

image

响应结果

image

数据库结构

image

image

下面方式会报错,StudentIn类型校验失败

image