抽象 class 的抽象和子classes

pydantic and subclasses of abstract class

我正在尝试将 pydantic 与如下所示的架构一起使用:

class Base(BaseModel, ABC):
    common: int

class Child1(Base):
    child1: int

class Child2(Base):
    child2: int

class Response(BaseModel):
    events: List[Base]


events = [{'common':1, 'child1': 10}, {'common': 2, 'child2': 20}]

resp = Response(events=events)

resp.events
#Out[49]: [<Base common=10>, <Base common=3>]

它只占用了基地class的领域而忽略了其余部分。我怎样才能将 pydantic 与这种继承一起使用?我希望事件是 Base

的子 classes 的实例列表

目前最好的方法是使用 Union,例如

class Response(BaseModel):
    events: List[Union[Child2, Child1, Base]]

请注意 Union 中的顺序:pydantic 会将您的输入数据与 Child2Child1Base 进行匹配;因此,您上面的事件数据应该得到正确验证。参见 this warning about Union order

将来 discriminators 可能会以更强大的方式做类似的事情。

this issue.

中还有更多相关信息