From aeed6afb427294c561dcc69ffdc2bf25d480c2f5 Mon Sep 17 00:00:00 2001 From: LouisGobert Date: Thu, 11 Apr 2024 18:29:40 +0200 Subject: [PATCH] Use field description for RootModel schema description when there is no docstring --- pydantic/_internal/_generate_schema.py | 3 +++ tests/test_root_model.py | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/pydantic/_internal/_generate_schema.py b/pydantic/_internal/_generate_schema.py index e07e68f6ac..aec44932be 100644 --- a/pydantic/_internal/_generate_schema.py +++ b/pydantic/_internal/_generate_schema.py @@ -215,6 +215,7 @@ def modify_model_json_schema( JsonSchemaValue: The updated JSON schema. """ from ..main import BaseModel + from ..root_model import RootModel json_schema = handler(schema_or_field) original_schema = handler.resolve_ref_schema(json_schema) @@ -229,6 +230,8 @@ def modify_model_json_schema( docstring = None if cls is BaseModel else cls.__doc__ if docstring and 'description' not in original_schema: original_schema['description'] = inspect.cleandoc(docstring) + elif issubclass(cls, RootModel) and cls.model_fields['root'].description: + original_schema['description'] = cls.model_fields['root'].description return json_schema diff --git a/tests/test_root_model.py b/tests/test_root_model.py index a4402b693d..50793b93df 100644 --- a/tests/test_root_model.py +++ b/tests/test_root_model.py @@ -657,3 +657,25 @@ def test_model_construction_with_invalid_generic_specification() -> None: class GenericRootModel(RootModel, Generic[T_]): root: Union[T_, int] + + +def test_model_with_field_description() -> None: + class AModel(RootModel): + root: int = Field(description='abc') + + assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer', 'description': 'abc'} + + +def test_model_with_both_docstring_and_field_description() -> None: + """Check if the docstring is used as the description when both are present.""" + + class AModel(RootModel): + """More detailed description""" + + root: int = Field(description='abc') + + assert AModel.model_json_schema() == { + 'title': 'AModel', + 'type': 'integer', + 'description': 'More detailed description', + }