django-orchestra/orchestra/contrib/webapps/serializers.py

70 lines
2.4 KiB
Python
Raw Normal View History

from django.db import models
2015-04-23 14:34:04 +00:00
from rest_framework import serializers
2014-10-15 21:18:50 +00:00
from orchestra.api.serializers import HyperlinkedModelSerializer
2015-04-05 10:46:24 +00:00
from orchestra.contrib.accounts.serializers import AccountSerializerMixin
2014-05-08 16:59:35 +00:00
2015-04-23 14:34:04 +00:00
from .models import WebApp, WebAppOption
class OptionSerializer(serializers.ModelSerializer):
class Meta:
model = WebAppOption
fields = ('name', 'value')
def to_representation(self, instance):
return {prop.name: prop.value for prop in instance.all()}
def to_internal_value(self, data):
return data
2014-05-08 16:59:35 +00:00
class DataField(serializers.Field):
def to_representation(self, data):
return data
2014-10-15 21:18:50 +00:00
class WebAppSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
2015-04-23 14:34:04 +00:00
options = OptionSerializer(required=False)
data = DataField()
2014-05-08 16:59:35 +00:00
class Meta:
model = WebApp
fields = ('url', 'id', 'name', 'type', 'options', 'data')
2014-10-15 21:18:50 +00:00
postonly_fields = ('name', 'type')
2015-04-23 14:34:04 +00:00
def __init__(self, *args, **kwargs):
super(WebAppSerializer, self).__init__(*args, **kwargs)
if isinstance(self.instance, models.Model):
type_serializer = self.instance.type_instance.serializer
if type_serializer:
self.fields['data'] = type_serializer()
2015-04-23 14:34:04 +00:00
def create(self, validated_data):
options_data = validated_data.pop('options')
webapp = super(WebAppSerializer, self).create(validated_data)
for key, value in options_data.items():
WebAppOption.objects.create(webapp=webapp, name=key, value=value)
return webap
def update(self, instance, validated_data):
options_data = validated_data.pop('options')
2015-04-23 19:46:23 +00:00
instance = super(WebAppSerializer, self).update(instance, validated_data)
2015-04-23 14:34:04 +00:00
existing = {}
for obj in instance.options.all():
existing[obj.name] = obj
posted = set()
for key, value in options_data.items():
posted.add(key)
try:
option = existing[key]
except KeyError:
option = instance.options.create(name=key, value=value)
else:
if option.value != value:
option.value = value
option.save(update_fields=('value',))
for to_delete in set(existing.keys())-posted:
existing[to_delete].delete()
return instance