Quantcast
Channel: User bavaza - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Answer by bavaza for Exclude fields from a pydantic class

$
0
0

Facing a similar issue, I ended up with (Pydantic 2):

from typing import Any, Annotatedfrom pydantic import BaseModel, Field, AfterValidatorfrom pydantic.json_schema import SkipJsonSchemaExcludedField = SkipJsonSchema[    Annotated[        Any,        Field(default=None, exclude=True),        AfterValidator(lambda s: None)    ]]class MyClass(BaseModel):        field_1: str = Field(description='Field 1')    field_2: dict = Field(description='Field 2')    field_3: list = Field(description='Field 3')class MyChildClass(MyClass):    field_2: ExcludedField = 'sentinel'    field_4: str = Field(description='Field 4')

Examples:

>>> MyChildClass(field_1='f1', field_3=['f3'], field_4='f4')MyChildClass(field_1='f1', field_2=None, field_3=['f3'], field_4='f4')>>> MyChildClass(field_1='f1', field_2={'a': 1, 'b': 2}, field_3=['f3'], field_4='f4')MyChildClass(field_1='f1', field_2=None, field_3=['f3'], field_4='f4')

ExcludedField explanation:

  • SkipJsonSchema excludes the field from the generated JSON schema (super useful if your use case is FastAPI)
  • Field(default=None, exclude=True) excludes field_2 from the model when exporting it (see here), and sets its default value to None.
  • The AfterValidator runs after validation, and coerces the actual value to None. This has the advantage, that even if the calling code passes field_2 to MyChildClass, it will be set to None.

Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>