Skip to content

Instantly share code, notes, and snippets.

@lukasni
Last active March 18, 2016 12:19
Show Gist options
  • Save lukasni/a2c78fba1569a881cd36 to your computer and use it in GitHub Desktop.
Save lukasni/a2c78fba1569a881cd36 to your computer and use it in GitHub Desktop.
Average messages by hour
SELECT ROUND(AVG(a.posts)) "Posts (avg)", post_hour
FROM (
SELECT count(id) posts, DATE(post_date) dateonly, EXTRACT(hour FROM post_date) post_hour
FROM message
GROUP BY post_hour, dateonly
) a
GROUP BY post_hour
ORDER BY post_hour;
def message_average_by_hour(request):
data = Message.objects.all() \
.extra(select={'day': connections[Message.objects.db].ops.date_trunc_sql('day', 'post_date')}) \
.extra({'hour':'extract(hour from post_date)'}) \
.values('day', 'hour') \
.annotate(count_items=Count('id'))
return JsonResponse(list(data), safe=False)
[
{"day": "2015-12-19T00:00:00Z", "hour": 21.0, "count_items": 1},
{"day": "2015-09-14T00:00:00Z", "hour": 13.0, "count_items": 4},
{"day": "2016-01-26T00:00:00Z", "hour": 21.0, "count_items": 2},
{"day": "2016-01-25T00:00:00Z", "hour": 6.0, "count_items": 6},
{"day": "2015-08-21T00:00:00Z", "hour": 10.0, "count_items": 5},
{"day": "2015-08-25T00:00:00Z", "hour": 13.0, "count_items": 1},
{"day": "2015-11-20T00:00:00Z", "hour": 10.0, "count_items": 1},
{"day": "2016-02-02T00:00:00Z", "hour": 7.0, "count_items": 35},
{"day": "2015-07-17T00:00:00Z", "hour": 6.0, "count_items": 2}
]
[
{"hour": 6.0, "average": 4}
{"hour": 7.0, "average": 35}
...
]
class Message(models.Model):
post_date = models.DateTimeField('Date posted')
username = models.CharField(max_length=50)
def __str(self):
return self.username
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment