Last active
February 7, 2023 08:16
-
-
Save akkuman/bb452364bc04ddc1d7886552318c4f5c to your computer and use it in GitHub Desktop.
pydantic 对于空字段的优化处理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import BaseModel, validator | |
class MyBaseModel(BaseModel): | |
@validator('*', pre=True) | |
def fill_values(cls, v, **kwargs): | |
# 对于一些字段,如果没有加 Optional 则会无法传递 null 值,就算设置了默认值也会校验失败 | |
# 此校验函数用来处理这部分字段,如果传递的值为假,且设置了默认值,则返回默认值 | |
# 注意,如果业务需求必须接收假值(比如空字符串),请不要使用此基类 | |
field_name = kwargs['field'].name | |
field = cls.__fields__[field_name] | |
if not field.required and not v: | |
return field.default | |
return v | |
from pydantic import BaseModel, root_validator, validator, Field | |
from typing import Dict, Any, List, Optional | |
class MyIP(BaseModel): | |
port_type: str = 'tcp' | |
fingerprint: Optional[List[str]] = [] | |
class_name: str = Field(default='', alias='class') | |
class Config: | |
allow_population_by_field_name = True | |
MyIP.parse_obj({"port_type": '', "fingerprint": [1,2], "class": '123'}) | |
# MyIP(port_type='tcp', fingerprint=['1', '2'], class_name='123') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment