抽象类的pydantic和子类

2024-04-25 17:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将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>]

它只占用基类的字段而忽略了其余的字段。我怎么能把pydantic用于这种继承呢?我希望事件是Base子类实例的列表


Tags: baseresponse模式commoneventsrespclassbasemodel
1条回答
网友
1楼 · 发布于 2024-04-25 17:44:24

现在最好的方法是使用Union,类似于

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

注意联合中的顺序:pydantic将根据Child2,然后Child1,然后{}匹配您的输入数据;因此您上面的事件数据应该是正确的。见this warning about ^{} order。在

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

this issue中还有关于相关事项的更多信息。在

相关问题 更多 >