You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

116 lines
2.9 KiB

from rest_framework import serializers
from apps.school.models import (
SchoolSchedule, SchoolScheduleImage, ImageObject
)
from .content import (
ImageObjectSerializer
)
from pprint import pprint
class GalleryImageCreateSerializer(serializers.ModelSerializer):
class Meta:
model = SchoolScheduleImage
fields = (
'id',
'img',
'created_at',
'update_at',
)
read_only_fields = (
'id',
'created_at',
'update_at',
)
class GalleryImageSerializer(GalleryImageCreateSerializer):
img = ImageObjectSerializer()
class SchoolScheduleSerializer(serializers.ModelSerializer):
start_at = serializers.TimeField(format='%H:%M')
schoolschedule_images = serializers.ListSerializer(
child=GalleryImageCreateSerializer(),
required=False,
)
class Meta:
model = SchoolSchedule
fields = (
'id',
'weekday',
'title',
'description',
'materials',
'age',
'month_price',
'day_discount',
'start_at',
'schoolschedule_images',
)
read_only_fields = (
'id',
)
def create(self, validated_data):
gallery = validated_data.pop('schoolschedule_images', [])
schoolschedule = super().create(validated_data)
self.dispatch_gallery(schoolschedule, gallery)
return schoolschedule
def update(self, instance, validated_data):
gallery = validated_data.pop('schoolschedule_images', [])
schoolschedule = super().update(instance, validated_data)
self.dispatch_gallery(schoolschedule, gallery)
return schoolschedule
def dispatch_gallery(self, schoolschedule, gallery):
for image in gallery:
imgs = SchoolScheduleImage.objects.filter(
schoolschedule=schoolschedule,
img=image['img']
)
if not imgs.exists():
si = SchoolScheduleImage.objects.create(
schoolschedule=schoolschedule,
img=image['img'],
)
def to_representation(self, instance):
return SchoolScheduleSerializerImg(instance, context=self.context).to_representation(instance)
class SchoolScheduleSerializerImg(serializers.ModelSerializer):
start_at = serializers.TimeField(format='%H:%M')
schoolschedule_images = serializers.ListSerializer(
child=GalleryImageSerializer(),
required=False,
)
class Meta:
model = SchoolSchedule
fields = (
'id',
'weekday',
'title',
'description',
'materials',
'age',
'month_price',
'day_discount',
'start_at',
'schoolschedule_images',
)
read_only_fields = (
'id',
)