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

52 lines
1.9 KiB
Python
Raw Permalink Normal View History

2014-05-08 16:59:35 +00:00
from rest_framework import serializers
2015-05-18 15:21:42 +00:00
from orchestra.api.serializers import (HyperlinkedModelSerializer,
SetPasswordHyperlinkedSerializer, RelatedHyperlinkedModelSerializer)
2015-04-05 10:46:24 +00:00
from orchestra.contrib.accounts.serializers import AccountSerializerMixin
2014-05-08 16:59:35 +00:00
from .models import Database, DatabaseUser
2014-05-08 16:59:35 +00:00
2015-05-18 15:21:42 +00:00
class RelatedDatabaseUserSerializer(AccountSerializerMixin, RelatedHyperlinkedModelSerializer):
2014-05-08 16:59:35 +00:00
class Meta:
model = DatabaseUser
2015-04-30 09:51:55 +00:00
fields = ('url', 'id', 'username')
2014-05-08 16:59:35 +00:00
2014-10-15 21:18:50 +00:00
class DatabaseSerializer(AccountSerializerMixin, HyperlinkedModelSerializer):
2015-04-23 14:34:04 +00:00
users = RelatedDatabaseUserSerializer(many=True) #allow_add_remove=True
2014-05-08 16:59:35 +00:00
class Meta:
model = Database
2015-04-30 09:51:55 +00:00
fields = ('url', 'id', 'name', 'type', 'users')
2014-10-15 21:18:50 +00:00
postonly_fields = ('name', 'type')
def validate(self, attrs):
2015-04-23 14:34:04 +00:00
attrs = super(DatabaseSerializer, self).validate(attrs)
for user in attrs['users']:
if user.type != attrs['type']:
raise serializers.ValidationError("User type must be" % attrs['type'])
return attrs
2014-05-08 16:59:35 +00:00
2015-05-18 15:21:42 +00:00
class RelatedDatabaseSerializer(AccountSerializerMixin, RelatedHyperlinkedModelSerializer):
2014-05-08 16:59:35 +00:00
class Meta:
model = Database
2015-04-30 09:51:55 +00:00
fields = ('url', 'id', 'name',)
2014-05-08 16:59:35 +00:00
2015-04-23 14:34:04 +00:00
class DatabaseUserSerializer(AccountSerializerMixin, SetPasswordHyperlinkedSerializer):
databases = RelatedDatabaseSerializer(many=True, required=False) # allow_add_remove=True
2014-05-08 16:59:35 +00:00
class Meta:
model = DatabaseUser
2015-04-30 09:51:55 +00:00
fields = ('url', 'id', 'username', 'password', 'type', 'databases')
2015-04-23 14:34:04 +00:00
postonly_fields = ('username', 'type', 'password')
def validate(self, attrs):
2015-04-23 14:34:04 +00:00
attrs = super(DatabaseUserSerializer, self).validate(attrs)
for database in attrs.get('databases', []):
if database.type != attrs['type']:
raise serializers.ValidationError("Database type must be" % attrs['type'])
return attrs