pydantic学习与使用-14.exclude_unset去掉未传值的字段

前言

使用 pydantic 定义数据模型,有些非必填的字段,我们希望在实例化时未传值的字段去掉,这样可以取值一些为None的字段。

遇到问题

age 和 address 是非必填字段

class User(BaseModel):
    name: str = ...
    tel: str = ...
    age: int = Field(None,)
    address: str = Field(None)


user = User(
    name='yoyo',
    tel='10086'
)
print(user.dict()) # {'name': 'yoyo', 'tel': '10086', 'age': None, 'address': None}

得到的结果, 没有传的字段会给到默认值

{'name': 'yoyo', 'tel': '10086', 'age': None, 'address': None}

exclude_unset去掉默认字段

可以通过 skip_defaults=True 参数跳过默认的设置项

print(user.dict(skip_defaults=True)) 

得到结果会有个警告:"skip_defaults" is deprecated and replaced by "exclude_unset"

DeprecationWarning: User.dict(): "skip_defaults" is deprecated and replaced by "exclude_unset"
  print(user.dict(skip_defaults=True)) # {'name': 'yoyo', 'tel': '10086', 'age': None, 'address': None}

{'name': 'yoyo', 'tel': '10086'}

"skip_defaults" 方法已经被 "exclude_unset" 替代了

print(user.dict(exclude_unset=True)) 

运行结果

{'name': 'yoyo', 'tel': '10086'}

这样就去掉了默认值为None的了。

posted @ 2022-10-04 20:29  上海-悠悠  阅读(550)  评论(0编辑  收藏  举报