Search code examples
pythonpydantic

How to build Pydantic models that do not produce nesting on serialization?


I am looking for a way to build a model Foo below, where serializing does not produce nesting (and of course Foo still does validation)

Desired behaviour: bar is validated according to Foo.

y = Bar(bar=Foo('xxx'))

Desired output:

print(y.json())
# {"bar": "xxx"}

Solution

  • You can use RootModel[str] for this.

    See this example:

    from pydantic import *
    
    class Foo(RootModel[str]):
        pass
    
    class Bar(BaseModel):
        bar: Foo
    
    y = Bar(bar=Foo('xxx'))
    
    print(y.model_dump_json())
    

    That way, you can have validation of Foo without having the nesting as you describe. That said, using Annotated here would probably make more sense.