Describe the bug
When using --set-default-enum-member, an IntEnum field default value 0 is not converted to the corresponding enum member (e.g. Status.integer_0). The generated model keeps the numeric default (0) instead of Status.integer_0.
To Reproduce
Example schema:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"status": {
"$ref": "#/$defs/Status",
"default": 0
}
},
"$defs": {
"Status": {
"type": "integer",
"enum": [0, 1]
}
}
}
Used commandline:
$ datamodel-codegen --input test.json --set-default-enum-member
Output:
from __future__ import annotations
from enum import IntEnum
from pydantic import BaseModel
class Status(IntEnum):
integer_0 = 0
integer_1 = 1
class Model(BaseModel):
status: Status | None = 0
Expected behavior
The default value should be converted to the corresponding enum member when --set-default-enum-member is enabled.
class Model(BaseModel):
status: Status | None = Status.integer_0
Version:
- OS: macOS
- Python version: 3.13.11
- datamodel-code-generator version: 0.53.1
Additional context
Confirmed locally: the issue is fixed for this case by applying the following changes.
In
|
if not model_field.default: |
:
- if not model_field.default:
+ if model_field.default is None:
In
|
field_default = str(field.default or "").strip("'\"") |
:
- field_default = str(field.default or "").strip("'\"")
+ field_default = str("" if field.default is None else field.default).strip("'\"")
Describe the bug
When using
--set-default-enum-member, anIntEnumfield default value0is not converted to the corresponding enum member (e.g.Status.integer_0). The generated model keeps the numeric default (0) instead ofStatus.integer_0.To Reproduce
Example schema:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "status": { "$ref": "#/$defs/Status", "default": 0 } }, "$defs": { "Status": { "type": "integer", "enum": [0, 1] } } }Used commandline:
$ datamodel-codegen --input test.json --set-default-enum-memberOutput:
Expected behavior
The default value should be converted to the corresponding enum member when
--set-default-enum-memberis enabled.Version:
Additional context
Confirmed locally: the issue is fixed for this case by applying the following changes.
In
datamodel-code-generator/src/datamodel_code_generator/parser/base.py
Line 2039 in 365419e
In
datamodel-code-generator/src/datamodel_code_generator/model/enum.py
Line 106 in 365419e