From d61066f519f79dc01f7855e3d6da6848ab21579c 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..03967b52 --- /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", + } + + label = getattr(self.target, "label", None) + return {**schema, "title": label} if label else schema