1

I have a table as below: Example Table

and I have a model as

class Hours(models.Model):
      name = model.Charfield(max_length =200)
      hours = DecimalField(max_digits = 6, decimal_places=2)

     def total_hours(self):
        queryset = Hours.objects.aggregate(total_hours=models.Sum('hours'))
        return queryset['total_hours']

now when I run the code I get all records have the to 37 instead of them having a running total.

where did I miss a step?

  • whenever you call total_hours its getting the sum of hours over all Hours objects. You'd need something like Hours.objects.filter(id__lte=self.id).aggregate(total_hours=models.Sum('hours')) for a running total – Henty Nov 15 '21 at 09:38
  • Hi @Henty thank you so much, please put this as an answer so I can accept it as a solution. its doing exactly what I needed – Umar Milanzi Snr Nov 15 '21 at 10:34

1 Answers1

3

Whenever you call total_hours its getting the sum of hours over all Hours objects. You'd need something like:

Hours.objects.filter(id__lte=self.id).aggregate(total_hours=models.Sum('hours')) 

for a running total

Henty
  • 603
  • 2
  • 7