Describe the bug
I have a schema which I think is very clearly saying 'this field is required, and takes a default.' But datamodel-codegen generates a model which accepts None alongside the specified type and its default, which doesn't seem quite right.
To Reproduce
Example schema:
{
"type": "object",
"required": ["a", "b"],
"additionalProperties": false,
"properties": {
"a": {
"type": "string"
},
"b": {
"type": "string",
"default": "default"
}
}
}
Used commandline:
$ datamodel-codegen --input test.json --use-default --output-model-type pydantic_v2.BaseModel --output result.json
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, ConfigDict
class Model(BaseModel):
model_config = ConfigDict(
extra='forbid',
)
a: str
b: Optional[str] = 'default'
Expected behavior
b
shouldn't be an Optional[str]
! Per https://docs.pydantic.dev/latest/migration/#required-optional-and-nullable-fields, that would mean b
is required, could be None, but by default is default
.
But my schema very clearly says that the field is required, cannot be None
(if I wanted to allow null values, I would have defined this field as a oneOf
that included a {"type": "null"}
), and takes a default of default
.
I would expect to get the below.
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, ConfigDict
class Model(BaseModel):
model_config = ConfigDict(
extra='forbid',
)
a: str
b: str = 'default'
which accurately displays my intention...if you give some value for b, it'd better be a string. But if it's not provided, that's okay, use 'default'. Maybe this is related to #670, but I'm not convinced. Pydantic supports the behavior I want already...it's this package which isn't handling it properly.
tldr, if I have a default on a required field, the code generator shouldn't be setting an optional unless null
is explicitly in the type definition.
Version:
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too