datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Invalid default object values generated when object defaults provided and --use-annotated specified

Open jkahovec opened this issue 8 months ago • 1 comments

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

jkahovec avatar Mar 25 '25 09:03 jkahovec

Related to https://github.com/koxudaxi/datamodel-code-generator/issues/1797

ilovelinux avatar May 12 '25 11:05 ilovelinux