问题
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