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的了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具