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

static code to generated models

Open aoliveiraenc opened this issue 1 year ago • 1 comments
trafficstars

Hey there, for the maintainers, thanks for that great library. I would appreciate a heads-up on something I'm trying to do, which is basically adding some static code to a generate model. I'm not sure Jinja would be suitable for that, since it's just a templating. Can someone give me a direction on the best approach for that? For example, for an Enum class:

class Foo(str, Enum):
    foo = 'foo'
    bar = 'bar'

I would like the generated model to override a special method:

class Foo(str, Enum):
    foo = 'foo'
    bar = 'bar'
    
    @classmethod
    def _missing_(cls, value):
        pass

I'm generating my models from an openapi.yml spec. Appreciate any thoughts or help!

aoliveiraenc avatar Feb 05 '24 12:02 aoliveiraenc

@aoliveiraenc Thank you for creating the issue We have considered what you want to achieve, but unfortunately, there is no easy way. However, it might be able to use because the fields in the extras_template_data are passed to the jinja2 template. Either way, you must create a custom jinja2 template and do additional processing for your specific model.

https://github.com/koxudaxi/datamodel-code-generator/blob/113dcd28a1b2ad6ec9f1850ac69221ab2f473a5e/datamodel_code_generator/model/typed_dict.py#L110

koxudaxi avatar Mar 16 '24 16:03 koxudaxi