Fix regression in handling of nested dataclasses in get_flat_models_from_field (#3819)

* add test for nested python dataclass schema generation

* fix handling of dataclasses in `get_flat_models_from_field`

* add change note
This commit is contained in:
Luis R
2022-05-11 20:02:37 +02:00
committed by GitHub
parent 74403c2f15
commit faee3301eb
3 changed files with 36 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
Fix nested Python dataclass schema regression in version 1.9
+4 -1
View File
@@ -419,10 +419,13 @@ def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) ->
# Handle dataclass-based models
if is_builtin_dataclass(field.type_):
field.type_ = dataclass(field.type_)
was_dataclass = True
else:
was_dataclass = False
field_type = field.type_
if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel):
field_type = field_type.__pydantic_model__
if field.sub_fields and not lenient_issubclass(field_type, BaseModel):
if field.sub_fields and (not lenient_issubclass(field_type, BaseModel) or was_dataclass):
flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models)
elif lenient_issubclass(field_type, BaseModel) and field_type not in known_models:
flat_models |= get_flat_models_from_model(field_type, known_models=known_models)
+31
View File
@@ -2884,3 +2884,34 @@ def test_alias_same():
},
},
}
def test_nested_python_dataclasses():
"""
Test schema generation for nested python dataclasses
"""
from dataclasses import dataclass as python_dataclass
@python_dataclass
class ChildModel:
name: str
@python_dataclass
class NestedModel:
child: List[ChildModel]
assert model_schema(dataclass(NestedModel)) == {
'title': 'NestedModel',
'type': 'object',
'properties': {'child': {'title': 'Child', 'type': 'array', 'items': {'$ref': '#/definitions/ChildModel'}}},
'required': ['child'],
'definitions': {
'ChildModel': {
'title': 'ChildModel',
'type': 'object',
'properties': {'name': {'title': 'Name', 'type': 'string'}},
'required': ['name'],
}
},
}