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

Type overrides

Open otonnesen opened this issue 11 months ago • 1 comments

Is your feature request related to a problem? Please describe. At my work, we have a few custom pydantic models that aren't really easy or possible to encode in an OpenAPI spec. As a result, we define them as pydantic.StrictStr and end up doing a lot of annoying back-and-forth rote type conversions whenever we interact with them on any code-generated models.

Describe the solution you'd like It would be great if we could just provide a mapping from OpenAPI spec model names to Python import strings and have datamodel codegen link to them instead. My rough idea for how this would work is to have a JSON file with the following structure: type-overrides.json

{
  "Some.PotentiallyNamespaced.CodeGeneratedType": "my_app.some_module.types.MyType",
  ...
}

This file could then be passed in as a filename (similar to how --aliases is handled), like datamodel-codegen ... --type-overrides type-overrides.json.

Describe alternatives you've considered Currently, we define complex models as pydantic.StrictStr and handle type conversions manually. This approach, however, is error-prone and requires a bunch of annoying boilerplate everywhere.

I briefly looked into trying to do this mapping with custom_templates, but it got ugly quick.

Additional context I'd be willing to work on the change myself if there's any appetite to add the feature. I have a sorta-working WIP branch here: https://github.com/otonnesen/datamodel-code-generator/tree/experiment/type-overrides.

otonnesen avatar Dec 27 '24 07:12 otonnesen

PR welcome 👍

gaborbernat avatar Feb 06 '25 20:02 gaborbernat

This is exactly what I'm searching for.

forman avatar Oct 01 '25 13:10 forman