WayToDoor
WayToDoor

Reputation: 1750

How to group objects by hour with django querysets?

Let's say I have a model that looks like this:

class Action(models.Model):
    timestamp = models.DateTimeField(default=timezone.now)
    # ...

How do I, in a view,

Basically, I want to have a graph showing how many Actions were done , with a resolution of an hour.

Upvotes: 2

Views: 416

Answers (1)

Enix
Enix

Reputation: 4579

You can leverage the ExtractHour function to get hour from your datetime field, and then group your records into a dict.

Sample code for your reference:

from collections import defaultdict
from django.db.models.functions import ExtractHour

# create a new field to extract hour from timestamp field
actions = Action.objects.annotate(hour=ExtractHour('created'))

# create a default dict to insert a list if key is not exist
results = defaultdict(lambda: [])
for row in actions:
    results[row.hour].append(row)

NOTE:

If you are using mysql database, pls remember to load timezone info before using Extract functions

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

Upvotes: 2

Related Questions