Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Sum values from different objects in Django?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"].

>Solution :

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'))
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading