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

Wrong field generation for Union[Interval, str]

Open andreas-wolf opened this issue 7 months ago • 0 comments

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

andreas-wolf avatar Apr 15 '25 10:04 andreas-wolf