datamodel-code-generator
datamodel-code-generator copied to clipboard
Const field not being detected when JSON schema $defs are used to generate code in pydantic_V2
Describe the bug When we use schema $def tag and define the subschemas separately if the first field in the object has a const value, the value is not detected but the object's name appears in the literal of the generated code.
To Reproduce Create a schema such as given below. Then generate the pydantic_v2 model using a command as follows
Example schema:
{
"title": "fruits",
"type": "object",
"properties": {
"families": {
"type": "object",
"discriminator": { "propertyName": "colour" },
"oneOf": [{ "$ref": "#/$defs/apple" },
{ "$ref": "#/$defs/orange" }]
}
},
"$defs": {
"apple": {
"type": "object",
"properties": {
"flavor": {
"const": "sweet"
}
}
},
"orange": {
"type": "object",
"properties": {
"flavor": {
"const": "sour"
}
}
}
}
}
Used command line:
$ datamodel-codegen --input schema.json --input-file-type jsonschema --output datamodel.py --output-model-type pydantic_v2.BaseModel
Expected behaviour Expected
class Fruits(BaseModel):
flavour: Literal['sweet'] = Field(
...
)
What I got
class Fruits(BaseModel):
flavour: Literal['apple'] = Field(
...
)