serializers.py 10.9 KB
Newer Older
asmundh's avatar
asmundh committed
1
2
3
4
"""Serializers for the workouts application
"""
from rest_framework import serializers
from rest_framework.serializers import HyperlinkedRelatedField
5
from workouts.models import Workout, Exercise, ExerciseInstance, WorkoutFile, RememberMe, ExerciseFile
asmundh's avatar
asmundh committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199


class ExerciseInstanceSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for an ExerciseInstance. Hyperlinks are used for relationships by default.

    Serialized fields: url, id, exercise, sets, number, workout

    Attributes:
        workout:    The associated workout for this instance, represented by a hyperlink
    """

    workout = HyperlinkedRelatedField(
        queryset=Workout.objects.all(), view_name="workout-detail", required=False
    )

    class Meta:
        model = ExerciseInstance
        fields = ["url", "id", "exercise", "sets", "number", "workout"]


class WorkoutFileSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for a WorkoutFile. Hyperlinks are used for relationships by default.

    Serialized fields: url, id, owner, file, workout

    Attributes:
        owner:      The owner (User) of the WorkoutFile, represented by a username. ReadOnly
        workout:    The associate workout for this WorkoutFile, represented by a hyperlink
    """

    owner = serializers.ReadOnlyField(source="owner.username")
    workout = HyperlinkedRelatedField(
        queryset=Workout.objects.all(), view_name="workout-detail", required=False
    )

    class Meta:
        model = WorkoutFile
        fields = ["url", "id", "owner", "file", "workout"]

    def create(self, validated_data):
        return WorkoutFile.objects.create(**validated_data)


class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for a Workout. Hyperlinks are used for relationships by default.

    This serializer specifies nested serialization since a workout consists of WorkoutFiles
    and ExerciseInstances.

    Serialized fields: url, id, name, date, notes, owner, owner_username, visiblity,
                       exercise_instances, files

    Attributes:
        owner_username:     Username of the owning User
        exercise_instance:  Serializer for ExericseInstances
        files:              Serializer for WorkoutFiles
    """

    owner_username = serializers.SerializerMethodField()
    exercise_instances = ExerciseInstanceSerializer(many=True, required=True)
    files = WorkoutFileSerializer(many=True, required=False)

    class Meta:
        model = Workout
        fields = [
            "url",
            "id",
            "name",
            "date",
            "notes",
            "owner",
            "owner_username",
            "visibility",
            "exercise_instances",
            "files",
        ]
        extra_kwargs = {"owner": {"read_only": True}}

    def create(self, validated_data):
        """Custom logic for creating ExerciseInstances, WorkoutFiles, and a Workout.

        This is needed to iterate over the files and exercise instances, since this serializer is
        nested.

        Args:
            validated_data: Validated files and exercise_instances

        Returns:
            Workout: A newly created Workout
        """
        exercise_instances_data = validated_data.pop("exercise_instances")
        files_data = []
        if "files" in validated_data:
            files_data = validated_data.pop("files")

        workout = Workout.objects.create(**validated_data)

        for exercise_instance_data in exercise_instances_data:
            ExerciseInstance.objects.create(workout=workout, **exercise_instance_data)
        for file_data in files_data:
            WorkoutFile.objects.create(
                workout=workout, owner=workout.owner, file=file_data.get("file")
            )

        return workout

    def update(self, instance, validated_data):
        """Custom logic for updating a Workout with its ExerciseInstances and Workouts.

        This is needed because each object in both exercise_instances and files must be iterated
        over and handled individually.

        Args:
            instance (Workout): Current Workout object
            validated_data: Contains data for validated fields

        Returns:
            Workout: Updated Workout instance
        """
        exercise_instances_data = validated_data.pop("exercise_instances")
        exercise_instances = instance.exercise_instances

        instance.name = validated_data.get("name", instance.name)
        instance.notes = validated_data.get("notes", instance.notes)
        instance.visibility = validated_data.get("visibility", instance.visibility)
        instance.date = validated_data.get("date", instance.date)
        instance.save()

        # Handle ExerciseInstances

        # This updates existing exercise instances without adding or deleting object.
        # zip() will yield n 2-tuples, where n is
        # min(len(exercise_instance), len(exercise_instance_data))
        for exercise_instance, exercise_instance_data in zip(
            exercise_instances.all(), exercise_instances_data
        ):
            exercise_instance.exercise = exercise_instance_data.get(
                "exercise", exercise_instance.exercise
            )
            exercise_instance.number = exercise_instance_data.get(
                "number", exercise_instance.number
            )
            exercise_instance.sets = exercise_instance_data.get(
                "sets", exercise_instance.sets
            )
            exercise_instance.save()

        # If new exercise instances have been added to the workout, then create them
        if len(exercise_instances_data) > len(exercise_instances.all()):
            for i in range(len(exercise_instances.all()), len(exercise_instances_data)):
                exercise_instance_data = exercise_instances_data[i]
                ExerciseInstance.objects.create(
                    workout=instance, **exercise_instance_data
                )
        # Else if exercise instances have been removed from the workout, then delete them
        elif len(exercise_instances_data) < len(exercise_instances.all()):
            for i in range(len(exercise_instances_data), len(exercise_instances.all())):
                exercise_instances.all()[i].delete()

        # Handle WorkoutFiles

        if "files" in validated_data:
            files_data = validated_data.pop("files")
            files = instance.files

            for file, file_data in zip(files.all(), files_data):
                file.file = file_data.get("file", file.file)

            # If new files have been added, creating new WorkoutFiles
            if len(files_data) > len(files.all()):
                for i in range(len(files.all()), len(files_data)):
                    WorkoutFile.objects.create(
                        workout=instance,
                        owner=instance.owner,
                        file=files_data[i].get("file"),
                    )
            # Else if files have been removed, delete WorkoutFiles
            elif len(files_data) < len(files.all()):
                for i in range(len(files_data), len(files.all())):
                    files.all()[i].delete()

        return instance

    def get_owner_username(self, obj):
        """Returns the owning user's username

        Args:
            obj (Workout): Current Workout

        Returns:
            str: Username of owner
        """
        return obj.owner.username

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
class ExerciseFileSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for a ExerciseFile. Hyperlinks are used for relationships by default.

    Serialized fields: url, id, owner, file, Exercise

    Attributes:
        owner:      The owner (User) of the ExerciseFile, represented by a username. ReadOnly
        Exercise:    The associate Exercise for this ExerciseFile, represented by a hyperlink
    """

    owner = serializers.ReadOnlyField(source="owner.username")
    exercise = HyperlinkedRelatedField(
        queryset=Exercise.objects.all(), view_name="exercise-detail", required=False
    )

    class Meta:
        model = ExerciseFile
        fields = ["url", "id", "owner", "file", "exercise"]

    def create(self, validated_data):
        return ExerciseFile.objects.create(**validated_data)
asmundh's avatar
asmundh committed
221
222
223
224
225
226
227
228
229

class ExerciseSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for an Exercise. Hyperlinks are used for relationships by default.

    Serialized fields: url, id, name, description, unit, instances

    Attributes:
        instances:  Associated exercise instances with this Exercise type. Hyperlinks.
    """
230
    owner_username = serializers.SerializerMethodField()
asmundh's avatar
asmundh committed
231
232
233
    instances = serializers.HyperlinkedRelatedField(
        many=True, view_name="exerciseinstance-detail", read_only=True
    )
234
    files = ExerciseFileSerializer(many=True, required=False)
asmundh's avatar
asmundh committed
235
236
    class Meta:
        model = Exercise
237
238
239
240
241
        fields = ["url", "id", "owner", "owner_username", "name", "description", "unit", "instances", "files"]
        extra_kwargs = {"owner": {"read_only": True}}
    
    def get_owner_username(self, obj):
        return obj.owner.username
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    
    def create(self, validated_data):
        files_data = []
        if "files" in validated_data:
            files_data = validated_data.pop("files")

        exercise = Exercise.objects.create(**validated_data)

        for file_data in files_data:
            ExerciseFile.objects.create(
                exercise=exercise, owner=exercise.owner, file=file_data.get("file")
            )
        return exercise

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name", instance.name)
        instance.description = validated_data.get("description", instance.description)
        instance.unit = validated_data.get("unit", instance.unit)
        instance.save()

        if "files" in validated_data:
            files_data = validated_data.pop("files")
            files = instance.files

            for file, file_data in zip(files.all(), files_data):
                file.file = file_data.get("file", file.file)

            # If new files have been added, creating new WorkoutFiles
            if len(files_data) > len(files.all()):
                for i in range(len(files.all()), len(files_data)):
                    ExerciseFile.objects.create(
                        exercise=instance,
                        owner=instance.owner,
                        file=files_data[i].get("file"),
                    )
            # Else if files have been removed, delete WorkoutFiles
            elif len(files_data) < len(files.all()):
                for i in range(len(files_data), len(files.all())):
                    files.all()[i].delete()
asmundh's avatar
asmundh committed
281

282
        return instance
asmundh's avatar
asmundh committed
283
284
285
286
287
288
289
290
291
292
293
294
295

class RememberMeSerializer(serializers.HyperlinkedModelSerializer):
    """Serializer for an RememberMe. Hyperlinks are used for relationships by default.

    Serialized fields: remember_me

    Attributes:
        remember_me:    Value of cookie used for remember me functionality
    """

    class Meta:
        model = RememberMe
        fields = ["remember_me"]