From 9ee57318b75a4662f609c23c7420f23914519033 Mon Sep 17 00:00:00 2001 From: Sonny Bakker Date: Fri, 23 Sep 2022 12:32:44 +0200 Subject: [PATCH] [#215] add `DurationFieldExtension` --- vng_api_common/extensions/fields/duration.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 vng_api_common/extensions/fields/duration.py diff --git a/vng_api_common/extensions/fields/duration.py b/vng_api_common/extensions/fields/duration.py new file mode 100644 index 00000000..fab42dcd --- /dev/null +++ b/vng_api_common/extensions/fields/duration.py @@ -0,0 +1,19 @@ +from drf_spectacular.extensions import OpenApiSerializerFieldExtension + + +class DurationFieldExtension(OpenApiSerializerFieldExtension): + target_class = "rest_framework.fields.DurationField" + match_subclasses = True + + def map_serializer_field(self, auto_schema, direction): + default_schema = auto_schema._map_serializer_field( + self.target, direction, bypass_extensions=True + ) + + schema = { + **default_schema, + "format": "duration", + } + + verbose_name = getattr(self.target, "label", None) + return {**schema, "title": verbose_name} if verbose_name else schema