[英]pydantic exclude multiple fields from model
In pydantic is there a cleaner way to exclude multiple fields from the model, something like:在 pydantic 中有一种更简洁的方法可以从 model 中排除多个字段,例如:
class User(UserBase):
class Config:
exclude = ['user_id', 'some_other_field']
I am aware that following works, but I was looking for something cleaner like django.我知道以下工作,但我正在寻找像 django 这样更清洁的东西。
class User(UserBase):
class Config:
fields = {'user_id': {'exclude':True},
'some_other_field': {'exclude':True}
}
Pydantic will exclude the class variables which begin with an underscore. Pydantic 将排除以下划线开头的 class 变量。 so if it fits your use case, you can rename your attribues.
因此,如果它适合您的用例,您可以重命名您的属性。
class User(UserBase):
_user_id=str
some_other_field=str
....
I wrote something like this for my json:我为我的 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())
you can overriding dict and other method like.您可以覆盖 dict 和其他方法,例如。
A possible solution is creating a new class based in the baseclass using create_model:一个可能的解决方案是使用 create_model 在基类中创建一个新的 class:
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')
Which will return:哪个会返回:
> UserExcluded(some_other='hola')
Which is a copy of the baseclass but with no parameter 'ID'.这是基类的副本,但没有参数“ID”。
If you have the id in the validators you may want also to exclude those validators.如果您在验证器中有 id,您可能还希望排除这些验证器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.