发布于2024-12-12 11:30 阅读(1012) 评论(0) 点赞(16) 收藏(2)
I would like to be able to define a field on a model that can be removed in all nested occurrences by calling model_dump
in whatever way. See below example for an attempt:
# Trying nested properties
from typing import Optional
from pydantic import BaseModel, Field, field_validator
class BaseModel2(BaseModel):
class_name: Optional[str] = Field(None, validate_default=True)
@field_validator("class_name")
@classmethod
def set_class_name(cls, v):
if v is None:
return cls.__name__
else:
raise ValueError("class_name must not be set")
class Level3(BaseModel2):
whatever: int = 10
class Level2(BaseModel2):
whatever: int
level3: Level3
class Level1(BaseModel2):
whenever: Optional[float] = 1.1
level2: Level2
m = Level1(whenever=3.14, level2=Level2(whatever=123, level3=Level3(whatever=20)))
print(m.model_dump(exclude={"class_name": True, "__all__": {"class_name"}}))
>>> {'whenever': 3.14, 'level2': {'whatever': 123, 'level3': {'class_name': 'Level3', 'whatever': 20}}}
What I would expect is that exclude
allows me to exclude all class_name
occurences, so far I haven't managed.
If the above is not possible, then maybe something else is. My ultimate aim is to allow a context specific model dump.
But crucially I do not want to change serialisation of a single field, I want to add some information (the class name of the model cls.__name__
) to the model serialisation. All subsequent models would inherit from it and also be able to dump that information. See this discussion how I could achieve this in V1 due to dict
being actually recursive! : https://github.com/pydantic/pydantic/discussions/11078
For instance, I could imagine working with the custom serializer, but then I would run into recursion problems OR (commented out) with overwriting the model_dump
functionality:
class BaseModel2(BaseModel):
# def model_dump(self, **kwargs):
# _dict = super().model_dump(serialize_as_any=True, **kwargs)
# # _dict["__vizro_model__"] = self.__class__.__name__
# return _dict
@model_serializer
def ser_model(self, info: SerializationInfo) -> Dict[str, Any]:
print("CONTEXT", info)
_dict = {} # self.model_dump()
_dict["__vizro_model__"] = self.__class__.__name__
return _dict
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/2046484/a721a852bf47023710b6/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!