From b881bde5027ba3f49f010afc633b48aaf53aa272 Mon Sep 17 00:00:00 2001 From: "T. Franzel" Date: Thu, 10 Jun 2021 22:57:42 +0200 Subject: [PATCH] serializer field deprecation #415 --- drf_spectacular/openapi.py | 3 +++ drf_spectacular/utils.py | 4 ++++ tests/test_regressions.py | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/drf_spectacular/openapi.py b/drf_spectacular/openapi.py index 971a3ba8..66bf3cf8 100644 --- a/drf_spectacular/openapi.py +++ b/drf_spectacular/openapi.py @@ -771,6 +771,9 @@ def _map_basic_serializer(self, serializer, direction): self._map_field_validators(field, schema) + if field.field_name in get_override(serializer, 'deprecate_fields', []): + schema['deprecated'] = True + properties[field.field_name] = safe_ref(schema) if is_patched_serializer(serializer, direction): diff --git a/drf_spectacular/utils.py b/drf_spectacular/utils.py index a10b2c89..24cf2db2 100644 --- a/drf_spectacular/utils.py +++ b/drf_spectacular/utils.py @@ -392,6 +392,7 @@ def decorator(f): def extend_schema_serializer( many: Optional[bool] = None, exclude_fields: Optional[List[str]] = None, + deprecate_fields: Optional[List[str]] = None, examples: Optional[List[OpenApiExample]] = None, ): """ @@ -402,6 +403,7 @@ def extend_schema_serializer( heuristic to acknowledge a non-list serializer. :param exclude_fields: fields to ignore while processing the serializer. only affects the schema. fields will still be exposed through the API. + :param deprecate_fields: fields to mark as deprecated while processing the serializer. :param examples: define example data to serializer. """ def decorator(klass): @@ -409,6 +411,8 @@ def decorator(klass): set_override(klass, 'many', many) if exclude_fields: set_override(klass, 'exclude_fields', exclude_fields) + if deprecate_fields: + set_override(klass, 'deprecate_fields', deprecate_fields) if examples: set_override(klass, 'examples', examples) return klass diff --git a/tests/test_regressions.py b/tests/test_regressions.py index c5795a72..f75acceb 100644 --- a/tests/test_regressions.py +++ b/tests/test_regressions.py @@ -1992,3 +1992,21 @@ class XViewset(viewsets.ReadOnlyModelViewSet): 'items': {'type': 'array', 'items': {'type': 'integer'}, 'readOnly': True}, 'readOnly': True } + + +def test_extend_schema_serializer_field_deprecation(no_warnings): + @extend_schema_serializer(deprecate_fields=['old']) + class XSerializer(serializers.Serializer): + old = serializers.IntegerField() + new = serializers.IntegerField() + + class XView(generics.ListCreateAPIView): + serializer_class = XSerializer + + schema = generate_schema('/x', view=XView) + assert schema['components']['schemas']['X']['properties']['new'] == { + 'type': 'integer', + } + assert schema['components']['schemas']['X']['properties']['old'] == { + 'type': 'integer', 'deprecated': True + }