copying model and updating field of pydantic
copying model and updating field
https://github.com/pydantic/pydantic/discussions/2710
from datetime import datetime from typing import List, Optional from pydantic import BaseModel, Field class User(BaseModel): id: int class Config: validate_assignment = True external_data = { 'id': 123 } user = User(**external_data) a = user.copy(update={'id': 'j'}) a.id = "s"
如何使用FastAPI和PyDantic BaseModel修补程序部分更新数据
https://cloud.tencent.com/developer/ask/sof/106632594
from fastapi import FastAPI, Response, status, HTTPException, Path from fastapi.encoders import jsonable_encoder from pydantic import BaseModel app = FastAPI() class Product(BaseModel): name: str price: float inventory: int @app.get("/posts/{id}") def get_a_post(id: int = Path(None, title='Prod ID')): cursor.execute('''SELECT * FROM public.products WHERE ID = %s''',(str(id),)) post = cursor.fetchone() if not post: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"product with id {id} was not found!") return post @app.patch("/posts/{id}", response_model=Product) def patch_posts(id: int, post: Product): stored_data = post stored_model = Product(**stored_data) update_data = post.dict(exclude_unset=True) updated_data = stored_model.copy(update=update_data) post = jsonable_encoder(updated_data) return{"partially updated product": post}
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [翻译] 为什么 Tracebit 用 C# 开发
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端