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}}