Converting to a dictionary solves this:
>>> data = Data(info=Info(data='test'))
>>> dict(data)
{'info': Info(data='test')}
Answer from Yaakov Bressler on Stack Overflowpython - How to Control Recursion Depth in Pydantic’s model_dump Serialization? - Stack Overflow
A better way to `construct` models recursively
python - Defining recursive models in Pydantic? - Stack Overflow
Recursively exclude all 'None' fields in a deeply nested Pydantic model?
Either put from __future__ import annotations at the top of the file, or change your annotation to List['Task'].
The relevant pydantic documentation is here: https://pydantic-docs.helpmanual.io/usage/postponed_annotations/
But the error in your question is not pydantic specific, that's just how type annotations work.
Expanding on the accepted answer from Alex Hall:
From the Pydantic docs, it appears the call to update_forward_refs() is still required whether or not annotations is imported.
from typing import List
from pydantic import BaseModel
class Task(BaseModel):
name: str
subtasks: List['Task'] = []
Task.update_forward_refs()
or
# python3.7+
from __future__ import annotations
from typing import List
from pydantic import BaseModel
class Task(BaseModel):
name: str
subtasks: List[Task] = []
Task.update_forward_refs()
https://pydantic-docs.helpmanual.io/usage/postponed_annotations/#self-referencing-models
So, I am ware of exclude_none, but it works on per-model-basis, meaning that in the case deeply nested models, you would have to add this to every submodel. In certain situations, especially working with 3rd party provided models, this is not really an option. Is there a workaround to this limitation?