簡體   English   中英

使用 response_model fastAPI 和 Pydantic 返回深度嵌套的 json 對象

[英]return deeply nested json objects with response_model fastAPI and Pydantic

這是我的架構文件

from pydantic import BaseModel
from typing import Optional


class HolidaySchema(BaseModel):
    year: int
    month: int
    country: str
    language: str


class HolidayDateSchema(BaseModel):
    name: str
    date: str
    holidays: HolidaySchema | None = None

    class Config:
        orm_mode = True

這是我的路由器

@router.get("/holidays/",response_model = List[HolidayDateSchema])

我想得到的回應是

[
    {
        "date": "2021-08-14",
        "name": "Independence Day",
        "holidays": { "year": 2022, "month":5, "country":"pk", "language":"en"},
        "id": 13
    },
]

現在它不支持響應 model 的 pydantic 模式,我不知道為什么,它給出了錯誤pydantic.error_wrappers.ValidationError: 2 validation errors for HolidayDateSchema並且value is not a valid dict

如果任何人都可以使用 response_model 指定獲得深度嵌套的 JSON 對象的最佳方法,那就太好了。

HolidaySchema 未配置orm_mode = True

對於要從 SQLAlchemy model 對象自動轉換的所有模型,您都需要這個。

class HolidaySchema(BaseModel):
    year: int
    month: int
    country: str
    language: str

    class Config:
        orm_mode = True

如果您想要所有模型的設置,您可以在通用 BaseModel 上配置該設置並從該設置繼承。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM