Skip to content

Inherited models as fields are reconstructed as base model #265

@koliyo

Description

@koliyo

I have a model which has a field of a another base-class model. I want this field to be able to contain any sub-class of this model. But when I assign to this field it gets reconstructed to the base model.

from pydantic import BaseModel, validator, PyObject, ValidationError, BaseConfig

class Foo(BaseModel):
    a: int


class FooSub(Foo):
    b: str


class Container(BaseModel):
    foo: Foo

f = Foo(a=1)
c1 = Container(foo=f)
# print(f'c1: {c1}')


fs = FooSub(a=2, b='hello')
c2 = Container(foo=fs)

# print(f'c2: {c2}')
print(f'fs: {fs} (id: {id(fs)})')
print(f'c2.foo: {c2.foo} ({id(c2.foo)})')

this prints

fs: FooSub a=2 b='hello' (id: 4566162824)
c2.foo: Foo a=2 (4566162696)

What I want is c2.foo to be the FooSub instance I created and assigned. How can I achieve this? I have tried using custom validators, but without success.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions