Home > Enterprise >  How to Sum values from different objects in Django?
How to Sum values from different objects in Django?

Time:11-25

I want to calculate the workout volume of each user, and then append it so I can use the value in chart.js.

This is calculated by multiplying the reps, series, and weight of all exercises in all workouts a user has.

I have the following models:

class Exercise(models.Model):
    exercise = models.CharField(max_length=166)
    series = models.IntegerField(null=True, validators=[RegexValidator(r'^[0-9]*$')])
    reps = models.IntegerField(null=True, validators=[RegexValidator(r'^[0-9]*$')])
    weight = models.DecimalField(max_digits=5, decimal_places=1, null=True, blank=True)

class Workout(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE)
    day = models.CharField(max_length=1, blank=True, null=True, verbose_name="Dias")
    exercises = models.ManyToManyField(Exercise, blank=True)

To try and calculate that workout volume, I used the following in views:

data = []

workout = Workout.objects.filter(member=request.user.member)

for p in workout:
    exercise = p.exercises.aggregate(total=Sum(F('reps') * F('series') * F('weight'))).values()

    for d in exercise:
        data.append(d)

This, in turn, returns the Sum of each single day. So, if a user has 2 workouts, it'll return (example) ["4350.0", "7350.0"]

How can I calculate the sum of all days. So, in the case of this example, the final value would be ["11700.0"].

CodePudding user response:

I hope this will give you the expected result,

result = Exercise.objects.filter(
    workout__member=request.user.member
).aggregate(
    total=Sum(F('reps') * F('series') * F('weight'))
)
  • Related