Skip to content

OpenAPI integer discriminator with multiple enum values generates string Literals #3073

@kkinugasa

Description

@kkinugasa

Describe the bug
When an OpenAPI discriminator property is defined as integer and a target schema has multiple allowed values, the generated model uses string literals instead of integer literals.

In the example below, Bar.kind is generated as Literal['2', '3'], but it should be Literal[2, 3].

Notably, the single-value case works correctly in the same schema: Foo.kind is generated as Literal[1].

To Reproduce

Example schema:

{
  "openapi": "3.0.3",
  "info": {
    "title": "Minimal Integer Discriminator",
    "version": "1.0.0"
  },
  "paths": {},
  "components": {
    "schemas": {
      "Base": {
        "oneOf": [
          { "$ref": "#/components/schemas/Foo" },
          { "$ref": "#/components/schemas/Bar" }
        ],
        "discriminator": {
          "propertyName": "kind",
          "mapping": {
            "1": "#/components/schemas/Foo",
            "2": "#/components/schemas/Bar",
            "3": "#/components/schemas/Bar"
          }
        }
      },
      "Foo": {
        "type": "object",
        "properties": {
          "kind": {
            "type": "integer",
            "enum": [1]
          }
        },
        "required": ["kind"]
      },
      "Bar": {
        "type": "object",
        "properties": {
          "kind": {
            "type": "integer",
            "enum": [2, 3]
          }
        },
        "required": ["kind"]
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input example.json --input-file-type openapi --output model.py

Output:

from __future__ import annotations

from enum import IntEnum
from typing import Literal

from pydantic import BaseModel, Field, RootModel


class Kind(IntEnum):
    integer_1 = 1


class Foo(BaseModel):
    kind: Literal[1]


class Kind1(IntEnum):
    integer_2 = 2
    integer_3 = 3


class Bar(BaseModel):
    kind: Literal['2', '3']


class Base(RootModel[Foo | Bar]):
    root: Foo | Bar = Field(..., discriminator='kind')

Expected behavior
Bar.kind should be generated as:

kind: Literal[2, 3]

instead of:

kind: Literal['2', '3']

Version:

  • OS: macOS
  • Python version: 3.13.11
  • datamodel-code-generator version: 0.56.0

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions