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

20 篇文章 8 订阅

前言

使用 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的了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值