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

56 lines
1.9 KiB
Python
Raw Normal View History

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
2014-10-15 21:18:50 +00:00
class WebAppSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
2015-04-23 14:34:04 +00:00
options = OptionSerializer(required=False)
2014-05-08 16:59:35 +00:00
class Meta:
model = WebApp
fields = ('url', 'name', 'type', 'options')
2014-10-15 21:18:50 +00:00
postonly_fields = ('name', 'type')
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')
instance = super(WebAppSerializer, self).update(validated_data)
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