I guess Aggregation is the Django way to do this, but suggested example would produce shitload of queries as Behesti said. And my guess is that that django ORM is really not built for number crunching (but i might be wrong here!)
I would maybe go with numpy (if you are really having huge array, i guess you need to do some partitioning):
The good sides using numpy is that its usually quite much faster than 'standard' python operations, but bad side is that its extra dependency.
import numpy
raw_array = [ # This is for testing the code, use .values_list( 'val1', 'val2' ) with db
[1 , 5 , 6],
[2 , 6 , 4],
[3 , 3 , 1],
[4 , 8 , 4],
[5 , 2 , 6],
[6 , 8 , 2],
[7 , 1 , 1],
]
arr = numpy.array( raw_array )
def sum_up_every_n_items( arr, n ):
res = numpy.zeros( (numpy.floor( arr.shape[0]/float(n) ), arr.shape[1]) )
arr = arr[ 0:res.shape[0]*n, : ] # Truncate, take only full N items
for loop in range(0,n): # Note: this is loop 0,1,2 if n=3 ! We do addition with numpy vectors!
res = res + arr[ loop::n, : ] # Get every n'th row from starting with offset
res = res / float(n)
return res
res = sum_up_every_n_items( arr, n=3 )
print res
outputs
[[ 2. 4.66666667 3.66666667]
[ 5. 6. 4. ]]