copying model and updating field of pydantic

lightsong發表於2024-11-18

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}

相關文章