I need to retrieve count of records created in each hour duration from midnight to present time. To do so the model contain a created_at
timestamp field which will record the created time.
The model definition is given bellow.
class Token(models.Model):
customer_name = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
remarks = models.TextField(null=True,blank=True)
modified_at = models.DateTimeField(auto_now =True)
The result am looking for like the following in SQL output
Intervel | count|
-----------------|
01:00 AM | 0 | # 00:00 to 01:00 AM
02:00 AM | 0 |
.......
10:00 AM | 20 |
11:00 AM | 5 |
........
03:00 PM | 5 |
------------------
I need to get model query that can do the above operation at the database end without loading all the records created in the day since from midnight to now then getting the count by running a forloop in the application. Kindly Help me in this..
You can first extract the items with the count, but that will not be sufficient, since there can be hours where there is no activity at all, and a database works under the "closed world assumption".
We thus query, with:
Here we thus first query for data, then post-process this to a dictionary, and finally set values for the hours in the range 1-24 that have no data.