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 @   上海-悠悠  阅读(747)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示