Search code examples
pythonfastapipydantic

How to Control Recursion Depth in Pydantic’s model_dump Serialization?


I have the following classes:

class Info:
  data: str
  

class Data:
  info: Info

When I call model_dump in Data class, pydantic will serialize the classe recursively as described here

This is the primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries.

Is there any way to stop the recursive part or specify how deep we want the serialisation go?

My desired output would be something like the following:

{
  "info": Info
}

instead of

{
  "info": {
    "data":"some data"
  }
}

I tried to search in documentation how to change this behaviour but didn't find anything.


Solution

  • Converting to a dictionary solves this:

    >>> data = Data(info=Info(data='test'))
    >>> dict(data)
    {'info': Info(data='test')}