Skip to content

Commit 89fc32e

Browse files
committed
docs: add example
1 parent 236a726 commit 89fc32e

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

README.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,38 @@
11
# pydantic-flatten-rootmodel
22

33
Library 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.

0 commit comments

Comments
 (0)