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

Prefix child model names with name of parent to avoid name collision

Open MinekPo1 opened this issue 1 year ago • 0 comments

Is your feature request related to a problem? Please describe. Some schemas include a member with a common name across multiple definitions, but uniquely defined inside each one.

synthetic, minimal example
{
	"$schema": "http://json-schema.org/draft-04/schema#",
	"title": "example",
	"type": "object",
	"definitions": {
		"A": {
			"type": "object",
			"properties": {
				"body": {
					"type": "object",
					"properties": {
						"a_data": {"type":"string"}
					},
					"required": ["a_data"]
				}
			},
			"required": ["body"]
		},
		"B": {
			"type": "object",
			"properties": {
				"body": {
					"type": "object",
					"properties": {
						"b_data": {"type":"string"}
					},
					"required": ["b_data"]
				}
			},
			"required": ["body"]
		}
	}
}

Currently, this is handled by creating a new definition for each one, with the name being derived from the key name and thus name collisions need to be avoided by adding numbers to later instances.

Describe the solution you'd like Prefix the model name with the parent model name. This is more readable and provides clearer disambiguation for developers.

IE, the model could look like
from __future__ import annotations

from pydantic import BaseModel


class Example(BaseModel):
    pass


class ABody(BaseModel):
    a_data: str


class A(BaseModel):
    body: ABody


class BBody(BaseModel):
    b_data: str


class B(BaseModel):
    body: BBody

(note that BBody would be currently named Body1)

Describe alternatives you've considered

  • Doing this manually
  • Not doing anything and accepting the worse readability and developer experience.

Additional context See DAP for an actual schema with this property, getting to Body11

MinekPo1 avatar Aug 06 '24 13:08 MinekPo1