Skip to content

Commit a800cea

Browse files
committed
get component name from meta attribute or class name
1 parent 3a29634 commit a800cea

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

rest_framework/schemas/openapi.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
import warnings
23
from operator import attrgetter
34
from urllib.parse import urljoin
@@ -109,20 +110,33 @@ def get_operation(self, path, method):
109110

110111
return operation
111112

113+
def _get_serializer_component_name(self, serializer):
114+
if not hasattr(serializer, 'Meta'):
115+
return None
116+
117+
if hasattr(serializer.Meta, 'schema_component_name'):
118+
return serializer.Meta.schema_component_name
119+
120+
# If the serializer has no Meta.schema_component_name, we use
121+
# the serializer's class name as the component name.
122+
component_name = serializer.__class__.__name__
123+
# We remove the "serializer" string from the class name.
124+
pattern = re.compile("serializer", re.IGNORECASE)
125+
return pattern.sub("", component_name)
126+
112127
def get_components(self, path, method):
113128
serializer = self._get_serializer(path, method)
114129

115130
if not isinstance(serializer, serializers.Serializer):
116131
return None
117132

118-
# If the model has no model, then the serializer will be inlined
119-
if not hasattr(serializer, 'Meta') or not hasattr(serializer.Meta, 'model'):
133+
component_name = self._get_serializer_component_name(serializer)
134+
135+
if component_name is None:
120136
return None
121137

122-
model_name = serializer.Meta.model.__name__
123138
content = self._map_serializer(serializer)
124-
125-
return {model_name: content}
139+
return {component_name: content}
126140

127141
def _get_operation_id(self, path, method):
128142
"""
@@ -490,8 +504,8 @@ def _get_serializer(self, path, method):
490504
return None
491505

492506
def _get_reference(self, serializer):
493-
model_name = serializer.Meta.model.__name__
494-
return {'$ref': '#/components/schemas/{}'.format(model_name)}
507+
component_name = self._get_serializer_component_name(serializer)
508+
return {'$ref': '#/components/schemas/{}'.format(component_name)}
495509

496510
def _get_request_body(self, path, method):
497511
if method not in ('PUT', 'PATCH', 'POST'):

tests/schemas/test_openapi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -758,4 +758,4 @@ def test_serializer_model(self):
758758
print(schema)
759759
assert 'components' in schema
760760
assert 'schemas' in schema['components']
761-
assert 'OpenAPIExample' in schema['components']['schemas']
761+
assert 'ExampleModel' in schema['components']['schemas']

0 commit comments

Comments
 (0)