datamodel-code-generator
datamodel-code-generator copied to clipboard
Wrong field generation for Union[Interval, str]
Describe the bug I get an incompatible types in assignment error for the generated model.
Incompatible types in assignment (expression has type "dict[str, int]", variable has type "Interval | str | None")
This code is generated:
my_field: Optional[Union[Interval, str]] = Field(
{'start': 2009, 'end': 2019},
title='My Field'
)
correct would be:
my_field: Optional[Union[Interval, str]] = Field(
default_factory=lambda: Interval.model_validate({'start': 2009, 'end': 2019}),
title='My Field'
)
The interval gets created correctly when the field is Optional[Interval]. So the problem seems to be related to the Union
To Reproduce
Example schema:
"my_field": {
"anyOf": [
{
"$ref": "#/components/schemas/Interval"
},
{
"const": "?all"
}
],
"title": "My Field",
"default": {
"start": 2009,
"end": 2019
}
},
Used commandline:
$ datamodel-codegen \
--input openapi.json \
--input-file-type openapi \
--output generated/models.py \
--output-model-type pydantic_v2.BaseModel \
--use-subclass-enum \
--capitalize-enum-members \
--target-python-version 3.12 \
--reuse-model \
--set-default-enum-member \
--field-constraints
Expected behavior see above
Version:
- OS: Ubuntu 24.04.2 LTS
- Python version: 3.12.9
- datamodel-code-generator version: 0.28.5
- openapi: 3.1.0
Additional context None