datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Strip default None from model fields when converting from yaml swagger to pydantic model

Open bill2605 opened this issue 1 year ago • 1 comments

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!

bill2605 avatar Jan 23 '24 03:01 bill2605

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.

9ao9ai9ar avatar Jul 30 '24 12:07 9ao9ai9ar