我尝试将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
子类实例的列表
现在最好的方法是使用
Union
,类似于注意联合中的顺序:pydantic将根据}匹配您的输入数据;因此您上面的事件数据应该是正确的。见this warning about ^{} order 。在
Child2
,然后Child1
,然后{将来discriminators可能会以更强大的方式做类似的事情。在
在this issue中还有关于相关事项的更多信息。在
相关问题 更多 >
编程相关推荐