I have a log table in my database which holds all user actions. In this table there is a column called 'money' which indic开发者_C百科ates how much money this user had on that day (there is also a 'timestamp' column for each log entry)
How can I retrieve data from that table grouped by week or month, aggregated with average value for money?
The easiest way to do this would be to precalculate the week and/or month and store that data into another field. Then the query is as easy as YourTable.objects.values('week', 'year').annotate(Avg('money))
.
You should also be able to do this with extra() parameters, but that is sometimes tricky. That would look like
YourTable.objects.extra(select={
'week': 'some_method_to_calculate_week_from_timestamp(timestamp)'
}).values('week').annotate(Avg('money'))
How you would calculate the week from timestamp in this second case would depend on your DB. If postgres the information you need would be in here: http://www.postgresql.org/docs/8.1/static/functions-datetime.html
精彩评论