mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
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:
@@ -0,0 +1 @@
|
||||
Fix nested Python dataclass schema regression in version 1.9
|
||||
+4
-1
@@ -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)
|
||||
|
||||
@@ -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'],
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user