File tree Expand file tree Collapse file tree 1 file changed +35
-1
lines changed
Expand file tree Collapse file tree 1 file changed +35
-1
lines changed Original file line number Diff line number Diff line change 11# pydantic-flatten-rootmodel
22
33Library to transform a [ Pydantic] ( https://pydantic.dev/ )
4- [ RootModel] ( https://docs.pydantic.dev/latest/api/root_model/ ) into a flattened BaseModel.
4+ [ RootModel] ( https://docs.pydantic.dev/latest/api/root_model/ )
5+ with discriminated unions into a flattened BaseModel.
6+
7+ ``` py
8+ from pydantic- flatten- rootmodel import flatten_root_model
9+
10+ class Cat (BaseModel ):
11+ pet_type: Annotated[Literal[" cat" ], Field()]
12+ meow: str
13+
14+
15+ class Dog (BaseModel ):
16+ pet_type: Annotated[Literal[" dog" ], Field()]
17+ bark: str
18+
19+ class Pet (RootModel[Cat | Dog]):
20+ root: Annotated[Cat | Dog, Field(discriminator = " pet_type" )]
21+
22+
23+ FlattenedPet = flatten_root_model(Pet)
24+ ```
25+
26+ would result in ` FlattenedPet ` to have this shape:
27+
28+ ``` py
29+ class FlattenedPet (BaseModel ):
30+ pet_type: Annotated[Union[Literal[" cat" ], Literal[" dog" ]]]
31+ bark: Union[str , None ]
32+ meow: Union[str , None ]
33+ ```
34+
35+ This can for example be leveraged by [ dlt] ( https://dlthub.com ) for it's
36+ [ schema definition] ( https://dlthub.com/docs/general-usage/resource#define-a-schema-with-pydantic ) .
37+ Without flattening it, the discriminated union is not recognized correctly
38+ when setting up the table schema.
You can’t perform that action at this time.
0 commit comments