datamodel-code-generator
datamodel-code-generator copied to clipboard
Strip default None from model fields when converting from yaml swagger to pydantic model
Would anyone know of a way to remove the enforced default:None when converting an OpenApi 3.0.1 yaml document to Pydantic models for later usage?
As of now I see that every model has the following (unless an default value is explicitly stated in the yaml):
self: Optional[str] = Field(
None,
description='blah blah'
)
My issue is that when comes time to validate a JSON response, some fields which should be part of the model against which the response is validated are ignored without error. However, I've noticed that when the None default field value is removed, then errors are captured (missing or invalid field).
Maybe I'm missing something here. I thought the --strip-default-none would remove None but it is not.
Any ideas would be appreciated.
Thanks!
A workaround is to use model_config = ConfigDict(extra="forbid") so that invalid fields will raise an error. For missing fields, you could either override the field defaults, or define custom validators so that these errors are spotted.