简体   繁体   中英

Count records per day in a Django Model where date is Unix

I'm trying to create a query that counts how many queries per day there were on a certain Django table. I found a bunch of examples about it but none was dealing with Unix data. Here is what my model looks like:

class myData(models.Model):
    user_id = models.IntegerField()
    user = models.CharField(max_length=150)
    query = models.CharField(max_length=100)
    unixtime = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'myData'

So the result i'm trying to get is something like: {'27/06/2020': 10, '26/06/2020': 15... }

The doubt i have is: should i use a raw MYSQL query or should i use Django's ORM?

I tried to make it with a raw query, but didn't get the expected output:

select FROM_UNIXTIME(`unixtime`, '26.06.2020') as ndate,
       count(id) as query_count
from myData
group by ndate

But it gave the following output:

ndate      query_count
26/06/2020 1
26/06/2020 1
26/06/2020 1
26/06/2020 1
....

Can anyone help me out on this? It doesn't make the difference whether the query is made with raw mysql or Django ORM, i just need a simple way to do this

You should read up on how to use the function FROM_UNIXTIME() , specially the allowed format string options.

Your query should probably be modified to something like this:

select FROM_UNIXTIME(unixtime, '%Y/%m/%d') as ndate,
       count(id) as query_count
from myData
group by ndate

Does that work for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM