欢迎光临
我们一直在努力

pydantic怎么去掉未传值的字段

这篇“pydantic怎么去掉未传值的字段”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“pydantic怎么去掉未传值的字段”文章吧。

前言

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

以上就是关于“pydantic怎么去掉未传值的字段”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注云搜网行业资讯频道。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。