Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Remove field from all nested models#11091

maxschulz-COL started this conversation inPydantic V2
Discussion options

I would like to be able to define a field on a model that can be removed in all nested occurrences when callingmodel_dumpat runtime (ie not usingexclude on theField definition) . See below example for an attempt:

# 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 thatexclude allows me to excludeallclass_name occurences, so far I haven't managed.

Ultimate aim

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 modelcls.__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 todict being actually recursive! :#11078

You must be logged in to vote

Replies: 0 comments

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Labels
None yet
1 participant
@maxschulz-COL

[8]ページ先頭

©2009-2025 Movatter.jp