datamodel-code-generator
datamodel-code-generator copied to clipboard
One `Literal` generated from `discriminator.mapping` doesn't have default
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:
- OS: macOS
- Python version: 3.12.3
- datamodel-code-generator version: 0.25.7
Additional context Add any other context about the problem here.