pydantic and subclasses of abstract class

六眼飞鱼酱① 提交于 2021-01-29 07:56:35

问题


I am trying to use pydantic with a schema that looks as the following:

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>]

It only took the field of the Base class and ignored the rest. How can I use pydantic with this kind of inheritance? I want events to be a list of instances of subclasses of Base


回答1:


The best approach right now would be to use Union, something like

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

Note the order in the Union matters: pydantic will match your input data against Child2, then Child1, then Base; thus your events data above should be correctly validated. See this warning about Union order.

In future discriminators might be able to do something similar to this in a more powerful way.

There's also more information on related matters in this issue.



来源:https://stackoverflow.com/questions/58301364/pydantic-and-subclasses-of-abstract-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!