From e8b1d707deb67f51fd67428cfad204610b0f5e85 Mon Sep 17 00:00:00 2001 From: ManishShah120 Date: Tue, 16 Mar 2021 13:58:23 +0530 Subject: [PATCH] Added the Create and Update method for nested serializer --- openwisp_controller/api/serializers.py | 42 ++++++++++++++++++-------- 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/openwisp_controller/api/serializers.py b/openwisp_controller/api/serializers.py index b5dc487e2..341fa026a 100644 --- a/openwisp_controller/api/serializers.py +++ b/openwisp_controller/api/serializers.py @@ -53,7 +53,18 @@ class Meta(BaseMeta): fields = '__all__' -class DeviceListSerializer(ValidatedModelSerializer): +class DeviceConfigSerializer(serializers.ModelSerializer): + config = serializers.JSONField() + context = serializers.JSONField() + + class Meta: + model = Config + fields = ['backend', 'status', 'templates', 'context', 'config'] + + +class DeviceListSerializer(serializers.ModelSerializer): + config = DeviceConfigSerializer(write_only=True) + class Meta(BaseMeta): model = Device fields = [ @@ -68,22 +79,29 @@ class Meta(BaseMeta): 'os', 'system', 'notes', + 'config', ] - -class DeviceConfigSerializer(serializers.ModelSerializer): - config = serializers.JSONField() - context = serializers.JSONField() - device = serializers.StringRelatedField() - - class Meta: - model = Config - fields = ['device', 'backend', 'status', 'templates', 'context', 'config'] + def create(self, validated_data): + # import ipdb; ipdb.set_trace() + config_data = validated_data.pop('config') + config_data.pop('templates') + device = Device.objects.create(**validated_data) + Config.objects.create(device=device, **config_data) + return device class DeviceDetailSerializer(serializers.ModelSerializer): - configuration = DeviceConfigSerializer(source='config') + config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device - fields = DeviceListSerializer.Meta.fields + ['configuration'] + fields = DeviceListSerializer.Meta.fields + ['config'] + + def update(self, instance, data): + # import ipdb; ipdb.set_trace() + config_templates = data['config']['templates'] + instance = self.instance or self.Meta.model(**data) + for template in config_templates: + instance.config.templates.add(template.pk) + return instance