Python - pydantic(2)嵌套模型


簡單的栗子

class User(BaseModel):
    id: int  # 必填字段
    name: str = "小菠蘿"  # 有默認值,選填字段
    signup_ts: Optional[datetime] = None
    friends: List[int] = []  # 列表中元素是 int 類型,或可以直接轉成 int 的類型


# 關鍵字參數
user = User(id="1",
            name="大菠蘿",
            signup_ts="2021-09-16 12:22")
print(user.dict())

# 字典解包傳參
data = {
    "id": "2",
    "name": "大大的菠蘿",
    "friends": [1, 2, 3]
}
user = User(**data)
print(user.dict())


# 輸出結果
{'id': 1, 'name': '大菠蘿', 'signup_ts': datetime.datetime(2021, 9, 16, 12, 22), 'friends': []}
{'id': 2, 'name': '大大的菠蘿', 'signup_ts': None, 'friends': [1, 2, 3]}

 

嵌套模型

可以使用模型本身作為數據類型提示來定義更復雜的分層數據結構

from typing import List
from pydantic import BaseModel


class Foo(BaseModel):
    count: int
    size: float = None


class Bar(BaseModel):
    apple = 'x'
    banana = 'y'


class Spam(BaseModel):
    foo: Foo
    bars: List[Bar]


f = Foo(count=2)
b = Bar()
s = Spam(foo=f, bars=[b])

print(s.dict())


# 輸出結果
{'bars': [{'apple': 'x', 'banana': 'y'}], 'foo': {'count': 2, 'size': None}}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM