Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
joel-wright opened this issue Dec 16, 2024 · 1 comment

Comments

@joel-wright
Copy link

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 joel-wright changed the title OpenAPI spec with a default value of an object causes issues with Pydantic Model OpenAPI spec with a default value of object/dict causes issues with Pydantic Model Dec 16, 2024
@joel-wright
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant