diff --git a/datamodel_code_generator/parser/jsonschema.py b/datamodel_code_generator/parser/jsonschema.py index ca1b6f179..9c0943f14 100644 --- a/datamodel_code_generator/parser/jsonschema.py +++ b/datamodel_code_generator/parser/jsonschema.py @@ -281,7 +281,8 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase] fields: List[DataModelFieldBase] = [] for field_name, field in properties.items(): - is_list = False + is_list: bool = False + is_union: bool = False field_types: List[DataType] field_name, alias = get_valid_field_name_and_alias(field_name) if field.ref: @@ -299,6 +300,7 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase] ) field_types = array_fields[0].data_types is_list = True + is_union = True elif field.anyOf: field_types = self.parse_any_of(field_name, field) elif field.allOf: @@ -341,6 +343,7 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase] data_types=field_types, required=required, is_list=is_list, + is_union=is_union, alias=alias, ) ) diff --git a/tests/data/openapi/nested_anyof.yaml b/tests/data/openapi/nested_anyof.yaml new file mode 100644 index 000000000..871435e4d --- /dev/null +++ b/tests/data/openapi/nested_anyof.yaml @@ -0,0 +1,27 @@ +openapi: 3.0.0 +info: + title: datamodel-code-generator bug example +components: + schemas: + Container: + allOf: + - type: object + required: + - contents + properties: + contents: + type: array + items: + anyOf: + - $ref: '#/components/schemas/Type1' + - $ref: '#/components/schemas/Type2' + Type1: + type: object + properties: + prop: + type: string + Type2: + type: object + properties: + prop: + type: string \ No newline at end of file diff --git a/tests/parser/test_openapi.py b/tests/parser/test_openapi.py index 89c5eae8b..0350877c2 100644 --- a/tests/parser/test_openapi.py +++ b/tests/parser/test_openapi.py @@ -845,6 +845,35 @@ class Error(BaseModel): ) +def test_openapi_parser_parse_nested_anyof(): + parser = OpenAPIParser( + BaseModel, + CustomRootType, + text=Path(DATA_PATH / 'nested_anyof.yaml').read_text(), + ) + assert ( + parser.parse() + == '''from __future__ import annotations + +from typing import List, Optional, Union + +from pydantic import BaseModel + + +class Type1(BaseModel): + prop: Optional[str] = None + + +class Type2(BaseModel): + prop: Optional[str] = None + + +class Container(BaseModel): + contents: List[Union[Type1, Type2]] +''' + ) + + def test_openapi_parser_parse_allof(): parser = OpenAPIParser( BaseModel, CustomRootType, text=Path(DATA_PATH / 'allof.yaml').read_text()