I'm having a hard time wrapping my head around this Django query. I could probably figure this out with SQL (and maybe I'll have to), but I was wondering if there is a way to do it with Django objects.
The model looks something like this (simplified for clarity):
class Stat(model.Models):
entry_date = models.DateTimeField()
quantity = models.PositiveIntegerField()
user = models.ForeignKey(User)
I need to return the sum (using annotate and sum, I'm guessing) of all the most recently added quantities by a user, grouped by month. It's a little hard to explain, but the quantity is not cumulative -- I only need to deal with the most recent records for a given user and a given month, and then I need to sum those quantities, and group them by month. If more explanation is needed, please say so.
UPDATE:
Here's some rough psudo-code, as requested. This code is not necessarily what I would expect, but it's roughly what I could do if, but in a slow, programmatic way. I'm hoping there is a way to do this via a single query for the sake of speed. (BTW, this is based on Manoj Govindan's code below.)
year = list_of_months_that_have_stats
users = all_users_in_database
for months in year:
for 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 that I'm trying to get the very last record for the given month. I'm doing this with order_by, but as far as I know this won't work -- it's just an illustration.
The code above won't work, of course. The missing piece of the puzzle is the descending order_by that gets only the first item in the query.