Skip to content

Commit

Permalink
Use field description for RootModel schema description when there is …
Browse files Browse the repository at this point in the history
…no docstring
  • Loading branch information
LouisGobert committed Apr 11, 2024
1 parent d294244 commit aeed6af
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pydantic/_internal/_generate_schema.py
Expand Up @@ -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)
Expand All @@ -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


Expand Down
22 changes: 22 additions & 0 deletions tests/test_root_model.py
Expand Up @@ -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',
}

0 comments on commit aeed6af

Please sign in to comment.