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

Pass reference to schema (or schema extensions) to templates

Open gresnick opened this issue 1 year ago • 0 comments

Is your feature request related to a problem? Please describe. It is possible to add custom extensions to a component schema which can be leveraged by the templates for more granular control on generation.

For example, I have the following component schema:

Icon:
      type: string
      description: ""
      
user.User:
      type: object
      required:
        - personal
        - financial
        - id
        - preferences
        - meta
      properties:
        id:
          $ref: "#/components/schemas/Id"
        meta:
          $ref: "#/components/schemas/user.Metadata"
        personal:
          $ref: "#/components/schemas/user.PersonalInformation"
        financial:
          $ref: "#/components/schemas/user.Financial"
        preferences:
          $ref: "#/components/schemas/user.Preferences"
      description: ""
      x-database-model:
        collection: users 

Notice the extension x-database-model extension. Having this information passed into the template could afford me the ability to conditionally change the base class, inject the collection information, or any additional changes I would require.

Describe the solution you'd like

I would like extensions to be passed into the template, so in templates/pydantic_v2/BaseModel.jinja2 I could do the following

...
class {{ class_name }}({{ base_class }}):{% if comment is defined %}  # {{ comment }}{% endif %}
{%- if description %}
    """
    {{ description | indent(4) }}
    """
{%- endif %}
{%- if extensions.get('x-database-model') %}
__collection__ = "{{ extensions['x-database-model']['collection'] }}"
{% endif %}
...

This gives me flexibility in augmenting templating by being able to pass in arbitrary information from the OpenAPI spec.

Describe alternatives you've considered I do not believe this is currently possible

gresnick avatar Nov 10 '24 12:11 gresnick