Skip to content

Field name changing in Pydantic V2 model #2364

@ollyhensby

Description

@ollyhensby

Describe the bug
I think this is due to the changes in this PR: #2355

We create the Pydantic model from JSON schema and then use that model but the name has appended _1 on the field name. Is this appropriate behaviour to change the field name?

Is this so that the field name isn't the same as the enumeration class name? If so, maybe we keep the field name the same and use Enum as a suffix for the enumeration class instead?

To Reproduce
Running this:

import pathlib
from datamodel_code_generator import DataModelType, InputFileType, generate
schema = {"title": "Test", "properties": {"Fruit": {"enum": ["apple", "banana"]}}}
output = pathlib.Path(__file__).parent / "test_model.py"
generate(
    json.dumps(schema),
    input_file_type=InputFileType.JsonSchema,
    input_filename="example.json",
    output=output,
    output_model_type=DataModelType.PydanticV2BaseModel,
    capitalise_enum_members=True,
)

produces

# generated by datamodel-codegen:
#   filename:  example.json
#   timestamp: 2025-03-26T17:43:52+00:00

from __future__ import annotations

from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field


class Fruit(Enum):
    APPLE = 'apple'
    BANANA = 'banana'


class Test(BaseModel):
    Fruit_1: Optional[Fruit] = Field(None, alias='Fruit')

Example schema:

{
    "title": "Test",
    "properties": {
        "Fruit": {
            "enum": [
                "apple",
                "banana"
            ]
        }
    }
}

Expected behaviour
Maybe instead we could produce:

# generated by datamodel-codegen:
#   filename:  example.json
#   timestamp: 2025-03-26T17:43:52+00:00

from __future__ import annotations

from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field


class FruitEnum(Enum):
    APPLE = 'apple'
    BANANA = 'banana'


class Test(BaseModel):
    Fruit: Optional[FruitEnum] = Field(None, alias='Fruit')

Version:

  • OS: Ubuntu 22.04.5 LTS
  • Python version: 3.13.2
  • datamodel-code-generator version: 0.28.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions