From b7d4902f663e8dd809ac7504128dc2a6daeed2e3 Mon Sep 17 00:00:00 2001 From: Klemen Pukl Date: Wed, 18 Dec 2024 16:15:31 +0100 Subject: [PATCH] refactor --- dynamicforms/fields.py | 19 ++++++++++++++++++- dynamicforms/serializers.py | 17 +---------------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/dynamicforms/fields.py b/dynamicforms/fields.py index 46b35927..532cfc2a 100644 --- a/dynamicforms/fields.py +++ b/dynamicforms/fields.py @@ -35,7 +35,24 @@ class AutoGeneratedField(dict): - pass + def get_serializer_field(self, name, serializer, extra_params=None): + from rest_framework.utils import model_meta + + if not hasattr(serializer, "_df_model"): + serializer._df_model = getattr(serializer.Meta, "model") + if not hasattr(serializer, "_df_info"): + serializer._df_info = model_meta.get_field_info(serializer._df_model) + if not hasattr(serializer, "_df_depth"): + serializer._df_depth = getattr(serializer.Meta, "depth", 0) + + if extra_params is None: + extra_params = self + field_class, field_kwargs = serializer.build_field( + name, serializer._df_info, serializer._df_model, serializer._df_depth + ) + field_kwargs.update(extra_params) + + return field_class(**field_kwargs) class BooleanField(FieldRenderMixin, ActionMixin, FieldHelpTextMixin, ConditionalVisibilityMixin, fields.BooleanField): diff --git a/dynamicforms/serializers.py b/dynamicforms/serializers.py index 62824326..5cd93bc5 100644 --- a/dynamicforms/serializers.py +++ b/dynamicforms/serializers.py @@ -302,18 +302,6 @@ def get_uniqueness_extra_kwargs(self, field_names: List[str], declared_fields: D Finds all ChoiceFields and RelatedFields and creates additional "-display" fields to show resolved display value in table """ - from rest_framework.utils import model_meta - - model = getattr(self.Meta, "model") - depth = getattr(self.Meta, "depth", 0) - info = None - - def _get_info(): - nonlocal info - if info is None: - info = model_meta.get_field_info(model) - return info - for field_name in field_names[:]: # existing extra as provided by get_extra_kwargs extra = extra_kwargs.get(field_name, dict()) @@ -321,10 +309,7 @@ def _get_info(): # serializer field: either what is declared as a Field instance in Serializer or AutogeneratedField s_field = declared_fields.get(field_name, getattr(self, field_name, None)) if isinstance(s_field, fields.AutoGeneratedField): - field_class, field_kwargs = self.build_field(field_name, _get_info(), model, depth) - field_kwargs.update(extra) - - s_field = field_class(**field_kwargs) + s_field = s_field.get_serializer_field(field_name, self, extra) # model field, if it exists try: