Skip to content
Snippets Groups Projects

Resolve "Refactor workouts/serializers.py"

Merged Ghost User requested to merge 24-refactor-workouts/serializers.py into master
1 file
+ 22
18
Compare changes
  • Side-by-side
  • Inline
@@ -132,7 +132,26 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
instance.save()
# Handle ExerciseInstances
self.handle_exercise_instances(instance, exercise_instances_data, exercise_instances)
# Handle WorkoutFiles
self.handle_workout_files(instance, validated_data)
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
# Helper method for updating exercise instances in workouts
def handle_exercise_instances(self, instance, exercise_instances_data, exercise_instances):
# 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))
@@ -149,7 +168,6 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
"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)):
@@ -161,9 +179,9 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
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
# Helper method for updating workout files
def handle_workout_files(self, instance, validated_data):
if "files" in validated_data:
files_data = validated_data.pop("files")
files = instance.files
@@ -184,20 +202,6 @@ class WorkoutSerializer(serializers.HyperlinkedModelSerializer):
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
class ExerciseSerializer(serializers.HyperlinkedModelSerializer):
"""Serializer for an Exercise. Hyperlinks are used for relationships by default.
Loading