在我的模型中,我有一些字段是强制性的。用户试图通过使用破折号(-)作为输入来避免填充这些字段。为了避免这种情况发生,我用Pydantic编写了一个自定义字符串类型。自定义类型检查输入是否应该更改为None,并检查是否允许为None。我的问题是,我的自定义类型不使用我的BaseModel的标志。例如anystr_strip_whitespace,以从字符串的开头和结尾删除空白。我想有配置从BaseModel也适用于我的自定义类型。因此,我希望任何人都可以帮助我解决关于在自定义类型中应用BaseModel标志的问题。
感谢所有的帮助
一些示例代码:
class MyBaseModel(BaseModel):
class Config:
anystr_strip_whitespace = True
class EmptyStrToNone(str):
@classmethod
def __get_validators__(cls):
yield cls.change_empty_string_to_none
@classmethod
def change_empty_string_to_none(cls, value: str, field: ModelField) -> Optional[str]:
"""If the field is Optional, the input which represents an empty string is set to None.
If the field is required, instead of returning None it raises an Exception."""
is_required = field.required
lowercase_value = str(value).lower()
if is_required:
# Faulty cases that raise an exception
# E.g. check in a dictionary if it has a string such as "not specified" that represents an empty string.
elif # Optional condition
return None
return str_validator(value)
您可以接收config
并使用它来决定是否应该剥离str
。来自Validators - pydantic:
关于验证器需要注意的几点:
[…]
您还可以添加以下参数的任意子集到签名中(名称必须匹配):
- […]
config
:模型配置
完整的示例:
from pydantic import BaseConfig, BaseModel
from pydantic.validators import str_validator
class MyStr(str):
@classmethod
def __get_validators__(cls):
yield str_validator
yield cls._strip_whitespace
# Yield more custom validators if needed
@classmethod
def _strip_whitespace(cls, value: str, config: BaseConfig) -> str:
if config.anystr_strip_whitespace:
return value.strip()
return value
class MyBaseModel(BaseModel):
my_str: MyStr
class Config:
anystr_strip_whitespace = True
print(MyBaseModel(my_str=" a "))
输出:
my_str='a'