Stay Hungry,Stay Foolish!

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}

 

posted @ 2024-11-18 18:29  lightsong  阅读(4)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel