poulpe/api/event/serializers.py

80 lines
2.7 KiB
Python
Raw Normal View History

2017-07-18 17:48:59 +02:00
from rest_framework import serializers
2017-07-20 15:08:19 +02:00
from event.models import Event, ActivityTag, Place, ActivityTemplate
2017-07-18 17:48:59 +02:00
class EventSerializer(serializers.HyperlinkedModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')
class Meta:
model = Event
fields = ('url', 'id', 'title', 'slug', 'created_by', 'creation_date',
2017-07-20 15:08:19 +02:00
'description', 'beginning_date', 'ending_date')
# TODO rajouter des permissions
class PlaceSerializer(serializers.HyperlinkedModelSerializer):
2017-07-21 17:03:33 +02:00
event = EventSerializer(allow_null=True)
2017-07-20 15:08:19 +02:00
class Meta:
model = Place
2017-07-21 17:03:33 +02:00
fields = ('url', 'id', 'name', 'description', 'event')
def update(self, instance, validated_data):
try:
data = validated_data.pop('event')
event = Event.objects.get_object_or_404(**data)
except KeyError:
event = None
[setattr(instance, key, value)
for key, value in validated_data.items()]
setattr(instance, 'event', event)
instance.save()
return instance
def create(self, validated_data):
ModelClass = self.Meta.model
try:
data = validated_data.pop('event')
event = Event.objects.get_object_or_404(**data)
except KeyError:
event = None
instance = ModelClass.objects.create(event=event, **validated_data)
return instance
2017-07-20 15:08:19 +02:00
# TODO rajouter des permissions
class ActivityTagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ActivityTag
fields = ('url', 'id', 'name', 'is_public', 'color',)
# TODO rajouter des permissions
class ActivityTemplateSerializer(serializers.HyperlinkedModelSerializer):
event = serializers.ReadOnlyField(source='event.title')
tags = ActivityTagSerializer(many=True)
class Meta:
model = ActivityTemplate
fields = ('url', 'id', 'title', 'event', 'is_public', 'has_perm',
'min_perm', 'max_perm', 'description', 'remarks', 'tags',)
def update(self, instance, validated_data):
tags_data = validated_data.pop('tags')
2017-07-21 17:03:33 +02:00
[setattr(instance, key, value)
for key, value in validated_data.items()]
2017-07-20 15:08:19 +02:00
instance.save()
tags = [ActivityTag.objects.get_or_create(**tag_data)[0]
for tag_data in tags_data]
instance.tags = tags
2017-07-21 17:03:33 +02:00
return instance
2017-07-20 15:08:19 +02:00
def create(self, validated_data):
tags_data = validated_data.pop('tags')
activity_template = ActivityTemplate.objects.create(**validated_data)
2017-07-21 17:03:33 +02:00
tags = [ActivityTag.objects.get_or_create(**tag_data)[0]
2017-07-20 15:08:19 +02:00
for tag_data in tags_data]
activity_template.tags = tags
return activity_template