Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.2k
Remove field from all nested models#11091
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
I would like to be able to define a field on a model that can be removed in all nested occurrences when calling # Trying nested propertiesfromtypingimportOptionalfrompydanticimportBaseModel,Field,field_validatorclassBaseModel2(BaseModel):class_name:Optional[str]=Field(None,validate_default=True)@field_validator("class_name")@classmethoddefset_class_name(cls,v):ifvisNone:returncls.__name__else:raiseValueError("class_name must not be set")classLevel3(BaseModel2):whatever:int=10classLevel2(BaseModel2):whatever:intlevel3:Level3classLevel1(BaseModel2):whenever:Optional[float]=1.1level2:Level2m=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 Ultimate aimIf 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 |
BetaWas this translation helpful?Give feedback.