Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use field description for RootModel schema description when there is … #9214

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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',
}