koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.44k stars 281 forks source link

One `Literal` generated from `discriminator.mapping` doesn't have default #2002

Open stevapple opened 2 weeks ago

stevapple commented 2 weeks ago

Describe the bug When a Literal field is generated from discriminator.mapping in an OpenAPI spec (to Pydantic v2), a default value is not generated even with --use-one-literal-as-default flag.

To Reproduce

Example schema:

openapi: "3.0.0"
info:
  version: "0.0.1"
  title: "Demo OpenAPI spec"
paths: {}
components:
  schemas:
    ResponseEvent:
      discriminator:
        propertyName: "type"
        mapping:
          start: "#/components/schemas/StartEvent"
          end: "#/components/schemas/EndEvent"
      oneOf:
        - $ref: "#/components/schemas/StartEvent"
        - $ref: "#/components/schemas/EndEvent"
    StartEvent:
      type: "object"
      properties:
        type:
          type: "string"
      required:
        - type
    EndEvent:
      type: "object"
      properties:
        type:
          type: "string"
      required:
        - type

Used commandline:

$ datamodel-codegen --input openapi.yml --input-file-type openapi --output model.py --output-model-type pydantic_v2.BaseModel --use-one-literal-as-default

Output:

# generated by datamodel-codegen:
#   filename:  openapi.yml
#   timestamp: 2024-06-12T14:20:48+00:00

from __future__ import annotations

from typing import Union

from pydantic import BaseModel, Field, RootModel
from typing_extensions import Literal

class StartEvent(BaseModel):
    type: Literal['start']

class EndEvent(BaseModel):
    type: Literal['end']

class ResponseEvent(RootModel[Union[StartEvent, EndEvent]]):
    root: Union[StartEvent, EndEvent] = Field(..., discriminator='type')

Expected behavior The type property of StartEvent and EndEvent should have default values because they are "single literal"s.

Version:

Additional context Add any other context about the problem here.