-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
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.
JakeSummers, askurihin, languitar, tobiasfshr, dettmar and 4 more