在 pydantic 中,有一种更干净的方法可以从模型中排除多个字段,例如:
class User(UserBase):
class Config:
exclude = ['user_id', 'some_other_field']
我知道以下方法有效,但我一直在寻找像 django 这样更干净的东西。
class User(UserBase):
class Config:
fields = {'user_id': {'exclude':True},
'some_other_field': {'exclude':True}
}
Pydantic 将排除以下划线开头的类变量。 因此,如果它适合您的用例,您可以重命名您的属性。
class User(UserBase):
_user_id=str
some_other_field=str
....
我为我的 json 写了这样的东西:
from pydantic import BaseModel
class CustomBase(BaseModel):
def json(self, **kwargs):
include = getattr(self.Config, "include", set())
if len(include) == 0:
include = None
exclude = getattr(self.Config, "exclude", set())
if len(exclude) == 0:
exclude = None
return super().json(include=include, exclude=exclude, **kwargs)
class User(CustomBase):
name :str = ...
family :str = ...
class Config:
exclude = {"family"}
u = User(**{"name":"milad","family":"vayani"})
print(u.json())
你可以覆盖字典和其他方法。
要排除字段,您还可以在
exclude
中使用 Field
:
from pydantic import BaseModel, Field
class Mdl(BaseModel):
val: str = Field(
exclude=True,
title="val"
)
但是,在
Config
类中添加排除参数的优点似乎是您可以使用 获取排除参数列表
print(Mdl.Config.exclude)
一个可能的解决方案是使用 create_model 在基类中创建一个新类:
from pydantic import BaseModel, create_model
def exclude_id(baseclass, to_exclude: list):
# Here we just extract the fields and validators from the baseclass
fields = baseclass.__fields__
validators = {'__validators__': baseclass.__validators__}
new_fields = {key: (item.type_, ... if item.required else None)
for key, item in fields.items() if key not in to_exclude}
return create_model(f'{baseclass.__name__}Excluded', **new_fields, __validators__=validators)
class User(BaseModel):
ID: str
some_other: str
list_to_exclude = ['ID']
UserExcluded = exclude_id(User, list_to_exclude)
UserExcluded(some_other='hola')
将返回:
> UserExcluded(some_other='hola')
这是基类的副本,但没有参数“ID”。
如果您在验证器中有 ID,您可能还想排除这些验证器。
对于 pydantic2,您可以使用执行以下操作:
class User(UserBase):
user_id: Annotated[int, Field(exclude=True)]
some_other_field: str
这样可以更干净