From fce3a5ac5d5b6a0fb9016e5089ff02f8aedb6ebb Mon Sep 17 00:00:00 2001 From: Sonny Bakker Date: Mon, 25 Nov 2024 17:12:21 +0100 Subject: [PATCH] Use separate `DjangoFilterExtension` to update `URLViewFilter` fields --- src/openklant/utils/query.py | 44 +++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/src/openklant/utils/query.py b/src/openklant/utils/query.py index 51d2eecf..31b580d0 100644 --- a/src/openklant/utils/query.py +++ b/src/openklant/utils/query.py @@ -1,30 +1,42 @@ # SPDX-License-Identifier: EUPL-1.2 # Copyright (C) 2024 Dimpact from drf_spectacular.contrib.django_filters import DjangoFilterExtension -from drf_spectacular.utils import OpenApiParameter from vng_api_common.utils import underscore_to_camel +from openklant.components.utils.filters import URLViewFilter + class CamelizeFilterExtension(DjangoFilterExtension): priority = 1 - def get_schema_operation_parameters(self, auto_schema, *args, **kwargs): - """ - camelize query parameters - """ - parameters = super().get_schema_operation_parameters( - auto_schema, *args, **kwargs + def resolve_filter_field( + self, auto_schema, model, filterset_class, field_name, filter_field + ) -> list[dict]: + results = super().resolve_filter_field( + auto_schema, model, filterset_class, field_name, filter_field ) - for parameter in parameters: - parameter["name"] = underscore_to_camel(parameter["name"]) + for result in results: + result["name"] = underscore_to_camel(result["name"]) + + return results + + +class UUIDURLFilterExtension(CamelizeFilterExtension): + priority = 2 + + def resolve_filter_field( + self, auto_schema, model, filterset_class, field_name, filter_field + ) -> list[dict]: + results = super().resolve_filter_field( + auto_schema, model, filterset_class, field_name, filter_field + ) - # reshape url fields which has incorrect field format - is_query = parameter["in"] == OpenApiParameter.QUERY - is_string = parameter["schema"]["type"] == "string" - is_url_field = parameter["name"].endswith("__url") + if not isinstance(filter_field, URLViewFilter): + return results - if all((is_query, is_string, is_url_field)): - parameter["schema"] = {"type": "string", "format": "uri"} + for result in results: + schema = result.setdefault("schema", {}) + schema.update({"type": "string", "format": "uri"}) - return parameters + return results