1

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:

  1. 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; ).
  2. 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.
  3. 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')) .
4

1 回答 1

1
  1. 每次你想要这个数据,你必须MyModel在python中查询所有并求和;这既不高效也不可扩展。
  2. 为什么你会保存UserProfile它似乎属于天数MyModel
  3. 我认为这应该是首选方法。它简单、优雅、易于操作。通过这样做,您将聚合放在数据库中
于 2013-03-16T13:34:01.550 回答