Skip to content

Use a class as a nested model, still access inheriting classes fields? #9198

Answered by uriyyo
AdrianDeAnda asked this question in Question
Discussion options

You must be logged in to vote

You can try to use SerializeAsAny:

from pydantic import BaseModel, SerializeAsAny


class Test1(BaseModel):
    age: int


class Test2(Test1):
    name: str


class Test3(BaseModel):
    what_test: SerializeAsAny[Test1]


test_model = Test2(age=10, name="test")
model = Test3(what_test=test_model)

print(model.model_dump())
{'what_test': {'age': 10, 'name': 'test'}}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@AdrianDeAnda
Comment options

Answer selected by AdrianDeAnda
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants