Skip to content

Commit

Permalink
Added the Create and Update method for nested serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
ManishShah120 committed Mar 16, 2021
1 parent dcd3d29 commit e8b1d70
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions openwisp_controller/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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

0 comments on commit e8b1d70

Please sign in to comment.