Describe the bug
datamodel-code-generator==0.54.1 generates an incorrect default_factory for inline object unions: it always validates through the first branch.
To Reproduce
Example schema:
{
"$defs": {
"A": { "properties": { "type": { "const": "a" } } },
"B": { "properties": { "type": { "const": "b" } } }
},
"properties": {
"x": {
"default": { "type": "b" },
"anyOf": [
{ "$ref": "#/$defs/A" },
{ "$ref": "#/$defs/B" }
]
}
}
}
Used commandline:
$ datamodel-codegen \
--input schema.json \
--input-file-type jsonschema \
--output out.py \
--output-model-type pydantic_v2.BaseModel \
--use-type-alias \
--target-python-version 3.12
Observed output:
class Model(BaseModel):
x: A | B | None = Field(default_factory=lambda: A.model_validate({"type": "b"}))
Observed behavior:
- mypy passes
- Model() fails at runtime because {"type": "b"} is validated as A
Expected:
- validate the default against the union and produce B, not hardcode branch 1
Describe the bug
datamodel-code-generator==0.54.1generates an incorrectdefault_factoryfor inline object unions: it always validates through the first branch.To Reproduce
Example schema:
{ "$defs": { "A": { "properties": { "type": { "const": "a" } } }, "B": { "properties": { "type": { "const": "b" } } } }, "properties": { "x": { "default": { "type": "b" }, "anyOf": [ { "$ref": "#/$defs/A" }, { "$ref": "#/$defs/B" } ] } } }Used commandline:
Observed output:
Observed behavior:
Expected: