Skip to content

Commit

Permalink
Use dosctrings from properties for field descriptions if available
Browse files Browse the repository at this point in the history
  • Loading branch information
spookylukey committed Apr 4, 2022
1 parent 6f5bd16 commit c589962
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
15 changes: 13 additions & 2 deletions drf_spectacular/openapi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import copy
import functools
import inspect
import re
import typing
from collections import defaultdict
Expand Down Expand Up @@ -1030,14 +1032,23 @@ def _map_response_type_hint(self, method):
if isinstance(hint, dict):
return hint

meta = {}
if not (
# partial does not produce helpful docstrings:
isinstance(method, functools.partial)
):
docstring = getattr(method, '__doc__', None)
if docstring:
meta['description'] = inspect.cleandoc(docstring)
try:
return resolve_type_hint(hint)
schema = resolve_type_hint(hint)
except UnableToProceedError:
warn(
f'unable to resolve type hint for function "{method.__name__}". Consider '
f'using a type hint or @extend_schema_field. Defaulting to string.'
)
return build_basic_type(OpenApiTypes.STR)
schema = build_basic_type(OpenApiTypes.STR)
return append_meta(schema, meta)

def _get_paginator(self):
pagination_class = getattr(self.view, 'pagination_class', None)
Expand Down
3 changes: 3 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ def __init__(self, instance):

@property
def calculated(self) -> int:
"""
My calculated property
"""
return self._instance.field_int

@property
Expand Down
7 changes: 7 additions & 0 deletions tests/test_fields.yml
Original file line number Diff line number Diff line change
Expand Up @@ -178,33 +178,40 @@ components:
additionalProperties: {}
field_sub_object_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_nested_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_model_int:
type: integer
readOnly: true
field_sub_object_cached_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_cached_nested_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_cached_model_int:
type: integer
readOnly: true
field_sub_object_py_cached_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_py_cached_nested_calculated:
type: integer
description: My calculated property
readOnly: true
field_sub_object_py_cached_model_int:
type: integer
readOnly: true
field_optional_sub_object_calculated:
type: integer
description: My calculated property
readOnly: true
nullable: true
field_sub_object_optional_int:
Expand Down

0 comments on commit c589962

Please sign in to comment.