Skip to content

Commit f55e5d1

Browse files
authored
Fix field name shadowing in Pydantic models and add corresponding tests (#2657)
1 parent 5aa57d2 commit f55e5d1

4 files changed

Lines changed: 63 additions & 1 deletion

File tree

src/datamodel_code_generator/parser/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1640,7 +1640,7 @@ def __change_field_name(
16401640
self,
16411641
models: list[DataModel],
16421642
) -> None:
1643-
if self.data_model_type != pydantic_model_v2.BaseModel:
1643+
if not issubclass(self.data_model_type, pydantic_model_v2.BaseModel):
16441644
return
16451645
for model in models:
16461646
if "Enum" in model.base_class:
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# generated by datamodel-codegen:
2+
# filename: field_name_shadows_class_name.json
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from typing import List, Optional
8+
9+
from pydantic import BaseModel, Field
10+
11+
12+
class Elem(BaseModel):
13+
temp: str
14+
15+
16+
class Model(BaseModel):
17+
Elem_1: Optional[List[Elem]] = Field(None, alias='Elem')
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"definitions": {
4+
"Elem": {
5+
"type": "object",
6+
"properties": {
7+
"temp": {
8+
"type": "string"
9+
}
10+
},
11+
"required": ["temp"]
12+
}
13+
},
14+
"type": "object",
15+
"properties": {
16+
"Elem": {
17+
"anyOf": [
18+
{
19+
"type": "array",
20+
"items": {
21+
"$ref": "#/definitions/Elem"
22+
}
23+
},
24+
{
25+
"type": "null"
26+
}
27+
]
28+
}
29+
}
30+
}

tests/main/jsonschema/test_main_jsonschema.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3775,3 +3775,18 @@ def test_main_use_frozen_field_dataclass(output_file: Path) -> None:
37753775
"--use-frozen-field",
37763776
],
37773777
)
3778+
3779+
3780+
@pytest.mark.benchmark
3781+
def test_main_field_name_shadows_class_name(output_file: Path) -> None:
3782+
"""Test field name shadowing class name is renamed with alias for Pydantic v2."""
3783+
run_main_and_assert(
3784+
input_path=JSON_SCHEMA_DATA_PATH / "field_name_shadows_class_name.json",
3785+
output_path=output_file,
3786+
input_file_type="jsonschema",
3787+
assert_func=assert_file_content,
3788+
extra_args=[
3789+
"--output-model-type",
3790+
"pydantic_v2.BaseModel",
3791+
],
3792+
)

0 commit comments

Comments
 (0)