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

OpenAPI spec with a default value of object/dict causes issues with Pydantic Model

Open joel-wright opened this issue 11 months ago • 1 comments
trafficstars

I'm trying to generate Pydantic V2 models from the Kubernetes OpenAPI Batch spec, but I'm running into issues when the default value in the OpenAPI spec is given as {}. This default value is copied directly into the model code, which generates warnings & results in invalid models when loading & relying on defaults.

One example:

UserWarning: Pydantic serializer warnings:
    Expected `ObjectMeta` but got `dict` with value `{}` - serialized value may not be as expected
    Expected `ObjectMeta` but got `dict` with value `{}` - serialized value may not be as expected
    Expected `ObjectMeta` but got `dict` with value `{}` - serialized value may not be as expected
    Expected `ObjectMeta` but got `dict` with value `{}` - serialized value may not be as expected

It seems it may be possible to solve this problem by adding the validate_default = True argument to the generated Field whenever the default value is an object/dict (in fact, I have worked around the issue locally by doing exactly this), but it would be nice to have a better solution for this problem.

To Reproduce

Generate a Pydantic V2 model from the kubernetes spec here: https://github.com/kubernetes/kubernetes/tree/master/api/openapi-spec

Used commandline:

$ datamodel-codegen --use-default-kwarg --use-union-operator --use-standard-collections --strict-nullable --use-exact-imports --input-file-type openapi --output-model-type pydantic_v2.BaseModel --target-python-version 3.10 --input kubernetes/api/openapi-spec/v3/apis__batch__v1_openapi.json --output k8s_openapi

Expected behavior Model code that produces a correct validated model when loading JobSpecs from JSON files.

Version:

  • OS: linux
  • Python version: 3.10
  • datamodel-code-generator version: [e.g. 0.26.4]

joel-wright avatar Dec 16 '24 16:12 joel-wright

I wonder if it's as simple as tweaking the jinja template for pydantic v2...

joel-wright avatar Dec 16 '24 20:12 joel-wright