datamodel-code-generator
datamodel-code-generator copied to clipboard
Invalid default object values generated when object defaults provided and --use-annotated specified
Describe the bug When default object values are provided in the openapi spec for a field typed as a model and --use-annotated is specified when generating the model plain dict is generated instead of a Pydantic model creation method which would create a Pydantic model instead
To Reproduce
An openapi schema default_object taken from the tests.
Generated model
class Bar(BaseModel):
foo: Annotated[Optional[Foo], Field()] = {'text': 'abc', 'number': 123}
baz: Annotated[Optional[List[Foo]], Field()] = [
{'text': 'abc', 'number': 123},
{'text': 'efg', 'number': 456},
]
nested_foo: Annotated[Optional[Foo], Field()] = 'default foo'
Used commandline:
datamodel-codegen --input default_object.yaml --output-model-type='pydantic_v2.BaseModel' --use-annotated --output output/ --input-file-type openapi
Expected model
class Bar(BaseModel):
foo: Annotated[Optional[Foo], Field()] = Foo.model_validate(
{"text": "abc", "number": 123}
)
baz: Annotated[Optional[List[Foo]], Field()] = [
Foo.model_validate(v)
for v in [{"text": "abc", "number": 123}, {"text": "efg", "number": 456}]
]
nested_foo: Annotated[Optional[Foo], Field()] = Foo.model_validate("default foo")
or possibly generate default_factory with a lambda function calling Pydantic model_validate function.
Version:
- OS: MacOS
- Python version: 3.12
- datamodel-code-generator version: 0.28.5
Related to https://github.com/koxudaxi/datamodel-code-generator/issues/1797