From c684e7d5e0bd6618093b69619b2052b64c3949f6 Mon Sep 17 00:00:00 2001 From: Matthias Date: Wed, 4 May 2022 16:57:39 +0200 Subject: [PATCH] Add generic serializer --- InvenTree/common/serializers.py | 42 +++++++++++++++++++++++++++++++++ InvenTree/plugin/serializers.py | 22 ++++++----------- 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/InvenTree/common/serializers.py b/InvenTree/common/serializers.py index 86d45cd881..b5b0b0928d 100644 --- a/InvenTree/common/serializers.py +++ b/InvenTree/common/serializers.py @@ -99,6 +99,48 @@ class UserSettingsSerializer(SettingsSerializer): ] +class GenericReferencedSettingSerializer(SettingsSerializer): + """ + Serializer for a GenericReferencedSetting model + + Args: + MODEL: model class for the serializer + EXTRA_FIELDS: fields that need to be appended to the serializer + field must also be defined in the custom class + """ + + MODEL = None + EXTRA_FIELDS = None + + def __init__(self, instance=None, data=..., **kwargs): + """Init overrides the Meta class to make it dynamic""" + # set Meta class + self.Meta = self.CustomMeta + self.Meta.model = self.MODEL + + # extend the fields + if not self.CustomMeta.DEFINED: + self.Meta.fields.extend(self.EXTRA_FIELDS) + self.CustomMeta.DEFINED = True + + # resume operations + super().__init__(instance, data, **kwargs) + + class CustomMeta: + """Scaffold for custom Meta class""" + DEFINED: bool = False + + fields = [ + 'pk', + 'key', + 'value', + 'name', + 'description', + 'type', + 'choices', + ] + + class NotificationMessageSerializer(InvenTreeModelSerializer): """ Serializer for the InvenTreeUserSetting model diff --git a/InvenTree/plugin/serializers.py b/InvenTree/plugin/serializers.py index 7a76c48067..6a7cfcf0c9 100644 --- a/InvenTree/plugin/serializers.py +++ b/InvenTree/plugin/serializers.py @@ -16,7 +16,7 @@ from django.utils import timezone from rest_framework import serializers from plugin.models import PluginConfig, PluginSetting -from common.serializers import SettingsSerializer +from common.serializers import GenericReferencedSettingSerializer class PluginConfigSerializer(serializers.ModelSerializer): @@ -128,22 +128,14 @@ class PluginConfigInstallSerializer(serializers.Serializer): return ret -class PluginSettingSerializer(SettingsSerializer): +class PluginSettingSerializer(GenericReferencedSettingSerializer): """ Serializer for the PluginSetting model """ - plugin = serializers.PrimaryKeyRelatedField(read_only=True) + MODEL = PluginSetting + EXTRA_FIELDS = [ + 'plugin', + ] - class Meta: - model = PluginSetting - fields = [ - 'pk', - 'key', - 'value', - 'name', - 'description', - 'type', - 'choices', - 'plugin', - ] + plugin = serializers.PrimaryKeyRelatedField(read_only=True)