11from rest_framework import serializers
2+ from django .db import transaction
23from .models import Task , Topic , Time
34
45
5- class TopicSerializer (serializers .ModelSerializer ):
6+ class TopicReadSerializer (serializers .ModelSerializer ):
67 class Meta :
78 model = Topic
89 fields = "__all__"
910
1011
11- class TimeSerializer (serializers .ModelSerializer ):
12+ class TimeReadSerializer (serializers .ModelSerializer ):
1213 class Meta :
1314 model = Time
1415 fields = "__all__"
1516
1617
1718class TaskReadSerializer (serializers .ModelSerializer ):
18- topics = TopicSerializer (many = True , read_only = True )
19- times = TimeSerializer (many = True , read_only = True )
19+ topics = TopicReadSerializer (many = True , read_only = True )
20+ times = TimeReadSerializer (many = True , read_only = True )
2021
2122 class Meta :
2223 model = Task
2324 fields = "__all__"
2425
26+ class TopicWriteSerializer (serializers .ModelSerializer ):
27+ class Meta :
28+ model = Topic
29+ fields = ["name" , "color_hex" ]
30+
31+ class TimeWriteSerializer (serializers .ModelSerializer ):
32+ class Meta :
33+ model = Time
34+ fields = ["day" , "start_time" , "end_time" , "repeating" ]
35+
2536class TaskWriteSerializer (serializers .ModelSerializer ):
37+ existing_topic_ids = serializers .PrimaryKeyRelatedField (
38+ many = True , queryset = Topic .objects .all (), write_only = True , required = False
39+ )
40+ new_topics = TopicWriteSerializer (many = True , write_only = True , required = False )
41+ times = TimeWriteSerializer (many = True , required = False )
42+
2643 class Meta :
2744 model = Task
28- fields = ["name" , "description" , "completed" ]
45+ fields = ["name" , "description" , "completed" , "existing_topic_ids" , "new_topics" , "times" ]
46+
47+ @transaction .atomic
48+ def create (self , validated_data ):
49+ existing_topics = validated_data .pop ("existing_topic_ids" , [])
50+ new_topics_data = validated_data .pop ("new_topics" , [])
51+ times_data = validated_data .pop ("times" , [])
52+
53+ task = Task .objects .create (** validated_data )
54+ user = task .user
55+
56+ if not user :
57+ raise serializers .ValidationError ("Task user is required to create topics." )
58+
59+ for topic in existing_topics :
60+ task .topics .add (topic )
61+
62+ for topic_data in new_topics_data :
63+ topic = Topic .objects .create (** topic_data , user = task .user )
64+ task .topics .add (topic )
65+
66+ Time .objects .bulk_create ([
67+ Time (task = task , ** time_data )
68+ for time_data in times_data
69+ ])
70+
71+ return task
0 commit comments