【问题标题】:pydantic and subclasses of abstract classpydantic 和抽象类的子类
【发布时间】:2020-02-06 15:02:44
【问题描述】:

我正在尝试将 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 子类的实例列表

【问题讨论】:

    标签: python pydantic


    【解决方案1】:

    目前最好的方法是使用Union,类似

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

    注意 Union 中的顺序很重要:pydantic 会将您的输入数据与Child2 匹配,然后是Child1,然后是Base;因此您上面的事件数据应该得到正确验证。见this warning about Union order

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

    this issue还有更多相关信息。

    【讨论】:

    • 非常喜欢。我正在尝试Union[List[Child1], List[Child2]] 并且没有工作。非常喜欢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多