Add generic serializer

This commit is contained in:
Matthias 2022-05-04 16:57:39 +02:00
parent 4125803e6d
commit c684e7d5e0
No known key found for this signature in database
GPG Key ID: AB6D0E6C4CB65093
2 changed files with 49 additions and 15 deletions

View File

@ -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

View File

@ -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)