Code:
MyModel(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
name = models.CharField()
somenum = models.IntegerField()
If I want to calculate sum of all the 'somenum'(last field in above model), then I can do this:
queryset.aggregate(Sum('somenum'))
My Requirement:
sum of (enddate-startdate)(means result is num of days) excluding (saturdays, and sundays).
I can do this using normal logic, but I think aggregate or someother way is preferred.
Ways i know:
- Loop every record of queryset, calculate num of days(excluding saturdays, sundays) for each record, and sum it during loop(like sum=0 before loop, inside loop sum += current_value; ).
- Write signal that does this calculation(sum) when model is saved, and save calculateed value to UserProfile. When we want value, we can get it from UserProfile, but I think this process is buggy.
- Add another field 'num_of_days' for MyModel shown above, and whenever a model is saved, the signal should perform calculation and should save that field. Then we can use queryset.aggregate(Sum('num_of_days')) .