from rest_framework import serializers from django.forms.models import model_to_dict from web.models.event import Event from web.models.event_category import EventCategory from web.models.event_tag import EventTag class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' def to_representation(self, instance): representation = super().to_representation(instance) event_categories = EventCategory.objects.filter(event=instance).filter(active=True).all() event_tags = EventTag.objects.filter(event=instance).filter(active=True).all() representation['location'] = { 'lng': instance.coordinates.x if instance.coordinates else None, 'lat': instance.coordinates.y if instance.coordinates else None } representation['categories'] = self._parse_categories(event_categories) representation['tags'] = self._parse_tags(event_tags) return representation def _parse_categories(self, event_categories): categories = [] if event_categories.exists(): for event_category in event_categories: categories.append({ 'id': event_category.category.id, 'name': event_category.category.name, 'description': event_category.category.description, '_meta': model_to_dict(event_category) }) return categories def _parse_tags(self, event_tags): tags = [] if event_tags.exists(): for event_tag in event_tags: tags.append({ 'id': event_tag.tag.id, 'name': event_tag.tag.name, '_meta': model_to_dict(event_tag) }) return tags