|
| 1 | +import re |
1 | 2 | import warnings
|
2 | 3 | from operator import attrgetter
|
3 | 4 | from urllib.parse import urljoin
|
@@ -109,20 +110,33 @@ def get_operation(self, path, method):
|
109 | 110 |
|
110 | 111 | return operation
|
111 | 112 |
|
| 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 | + |
112 | 127 | def get_components(self, path, method):
|
113 | 128 | serializer = self._get_serializer(path, method)
|
114 | 129 |
|
115 | 130 | if not isinstance(serializer, serializers.Serializer):
|
116 | 131 | return None
|
117 | 132 |
|
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: |
120 | 136 | return None
|
121 | 137 |
|
122 |
| - model_name = serializer.Meta.model.__name__ |
123 | 138 | content = self._map_serializer(serializer)
|
124 |
| - |
125 |
| - return {model_name: content} |
| 139 | + return {component_name: content} |
126 | 140 |
|
127 | 141 | def _get_operation_id(self, path, method):
|
128 | 142 | """
|
@@ -490,8 +504,8 @@ def _get_serializer(self, path, method):
|
490 | 504 | return None
|
491 | 505 |
|
492 | 506 | 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)} |
495 | 509 |
|
496 | 510 | def _get_request_body(self, path, method):
|
497 | 511 | if method not in ('PUT', 'PATCH', 'POST'):
|
|
0 commit comments