django - Summing on only the most recently added record -


i'm having hard time wrapping head around django query. figure out sql (and maybe i'll have to), wondering if there way django objects.

the model looks (simplified clarity):

class stat(model.models):     entry_date = models.datetimefield()     quantity = models.positiveintegerfield()     user = models.foreignkey(user) 

i need return sum (using annotate , sum, i'm guessing) of added quantities user, grouped month. it's little hard explain, quantity not cumulative -- need deal recent records given user , given month, , need sum quantities, , group them month. if more explanation needed, please so.

update:

here's rough psudo-code, requested. code not expect, it's if, in slow, programmatic way. i'm hoping there way via single query sake of speed. (btw, based on manoj govindan's code below.)

year = list_of_months_that_have_stats users = all_users_in_database months in year:     user in users:         sum = stat.object.filter(user=user, entry_date__month=month).order_by('-entry_date')[0].aggregate(sum=sum('quantity'))         final_output[month] = sum 

also, notice i'm trying last record given month. i'm doing order_by, far know won't work -- it's illustration.

the code above won't work, of course. missing piece of puzzle descending order_by gets first item in query.

i not sure understand want. see answer below , correct me if not getting right.

i need deal recent records given user , given month, , need sum quantities, , group them month.

(emphasis added). if need, can use filter in combination aggregate, shown below.

from django.db.models import sum q = stat.objects.filter(user = user, entry_date__month = 10).aggregate(     sum = sum('quantity')) print q # {'sum': 14} 

the filter conditions ensure have required user , month part of entry_date matches month want (in case october, therefore 10). can sum quantity user/month combination.

update

if want sum user per each month (i guessing here meant "group them month") can try this:

select = dict(month = 'extract(month entry_date)') q = stat.objects.filter(user = user).extra(       select = select).values('month').annotate(       sum = sum('quantity'))  print q # [{'sum': 14, 'month': 10.0}, {'sum': 6, 'month': 9.0}] 

here quick explanation.

  1. extra used specify want extract month part date. database specific. in case syntax extract(month entry_date) specific postgresql.

  2. use values mention need month. important. if leave out values part fields fetched , won't effect need.

  3. finally annotate each record sum('quantity'). returns sum each month.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -