我正在尝试将 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>]
它只获取了 Base 类的字段,忽略了其余部分。我如何将 pydantic 与这种继承一起使用?我希望事件是子类实例的列表Base
现在最好的方法是使用Union
, 就像是
class Response(BaseModel):
events: List[Union[Child2, Child1, Base]]
请注意 Union 中的顺序很重要:pydantic 会将您的输入数据与Child2
, then Child1
, then Base
;因此,您的上述事件数据应该得到正确验证。看这个警告关于Union order https://pydantic-docs.helpmanual.io/usage/types/#unions.
在未来歧视者 https://github.com/samuelcolvin/pydantic/issues/619也许能够以更强大的方式做类似的事情。
还有更多有关相关事宜的信息这个问题 https://github.com/samuelcolvin/pydantic/issues/854.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)