Skip to content

Commit eb7cdca

Browse files
authored
Fix missing imports for nested references when using --collapse-root-models (#2631)
* Add support for collapsing nested references in root models * Refactor nested reference schemas to use consistent naming conventions
1 parent a9b4f54 commit eb7cdca

4 files changed

Lines changed: 60 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
@@ -1451,7 +1451,7 @@ def __collapse_root_models( # noqa: PLR0912
14511451
else: # pragma: no cover
14521452
continue
14531453

1454-
for d in root_type_field.data_type.data_types:
1454+
for d in copied_data_type.all_data_types:
14551455
if d.reference is None:
14561456
continue
14571457
from_, import_ = full_path = relative(model.module_name, d.full_name)
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: collapse_root_models_nested_reference.json
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from typing import List
8+
9+
from pydantic import BaseModel
10+
11+
12+
class SomeRef(BaseModel):
13+
id: str
14+
15+
16+
class Model(BaseModel):
17+
refs: List[SomeRef]
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"type": "object",
4+
"properties": {
5+
"refs": {
6+
"$ref": "#/$defs/SomeRefs"
7+
}
8+
},
9+
"required": [
10+
"refs"
11+
],
12+
"$defs": {
13+
"SomeRefs": {
14+
"type": "array",
15+
"items": {
16+
"$ref": "#/$defs/SomeRef"
17+
}
18+
},
19+
"SomeRef": {
20+
"type": "object",
21+
"properties": {
22+
"id": {
23+
"type": "string"
24+
}
25+
},
26+
"required": [
27+
"id"
28+
]
29+
}
30+
}
31+
}

tests/main/jsonschema/test_main_jsonschema.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3157,6 +3157,17 @@ def test_main_jsonschema_collapse_root_models_with_optional(output_file: Path) -
31573157
)
31583158

31593159

3160+
def test_main_jsonschema_collapse_root_models_nested_reference(output_file: Path) -> None:
3161+
"""Ensure nested references inside root models still get imported when collapsing."""
3162+
run_main_and_assert(
3163+
input_path=JSON_SCHEMA_DATA_PATH / "collapse_root_models_nested_reference.json",
3164+
output_path=output_file,
3165+
input_file_type="jsonschema",
3166+
assert_func=assert_file_content,
3167+
extra_args=["--collapse-root-models"],
3168+
)
3169+
3170+
31603171
def test_main_jsonschema_file_url_ref(tmp_path: Path) -> None:
31613172
"""Test that file:// URL $ref is resolved correctly."""
31623173
pet_schema = {

0 commit comments

Comments
 (0)