datamodel-code-generator
datamodel-code-generator copied to clipboard
JsonSchema conversion adds None as default when isn't required & using null type
Describe the bug When converting JsonSchema, if a field is defined as not required and with a null type, the converter creates a default None value for this field To Reproduce
Example schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"a": {
"type": "object",
"required": [
"b"
],
"properties": {
"c": {
"title": "c",
"type": [
"string",
"null"
]
},
"b": {
"title": "b",
"type": [
"string",
"null"
]
}
},
"additionalProperties": false
}
},
"$ref": "#/definitions/a"
}
python
# generated by datamodel-codegen:
# filename: request_schema.json
# timestamp: 2022-05-22T13:39:44+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, Extra, Field
class A(BaseModel):
class Config:
extra = Extra.forbid
c: Optional[Optional[str]] = Field(None, title='c')
b: Optional[str] = Field(..., title='b')
class Model(BaseModel):
__root__: A
Used commandline:
$ datamodel-codegen --input <above json schema> --output <python file>
Expected behavior
python
# generated by datamodel-codegen:
# filename: request_schema.json
# timestamp: 2022-05-22T13:39:44+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, Extra, Field
class A(BaseModel):
class Config:
extra = Extra.forbid
c: Optional[Optional[str]] = Field(..., title='c')
b: Optional[str] = Field(..., title='b')
class Model(BaseModel):
__root__: A
Version:
- OS: macos
- Python version: 3.8.6
- datamodel-code-generator version: datamodel-code-generator==0.12.0
Additional context Ive tried also with --strip-default-none, and the output is the same.
@alonbeilis I'm sorry for my late reply.
c: Optional[Optional[str]] = Field(..., title='c')
I think the field is required in Pydantic.
But, you defined the field as not required in your schema 🤔
I'm encountering a similar problem: A field i set to nullable in the schema:
...
"forretningshændelse": {
"description": "EAID_1CE948DD_FC3D_4638_8913_A2D35A00F64D",
"type": ["string", "null"]
},
...
But the resulting generated code is:
...
forretningshændelse: Optional[Optional[str]] = Field(
None, description='EAID_1CE948DD_FC3D_4638_8913_A2D35A00F64D'
)
...
Expected output:
...
forretningshændelse: Optional[str] = Field(
None, description='EAID_1CE948DD_FC3D_4638_8913_A2D35A00F64D'
)
...
Why is it wrapped twice as Optional? :thinking:
I solved it manually by substituting ["string", "null"] for "string".
@nymann
I'm sorry for my too-late reply.
I have released the PR as 0.15.0
Thank you very much!!