简体   繁体   English

每天计算 Django Model 中的记录,其中日期为 Unix

[英]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.我正在尝试创建一个查询,该查询计算某个 Django 表上每天有多少查询。 I found a bunch of examples about it but none was dealing with Unix data.我找到了一堆关于它的例子,但没有一个是处理 Unix 数据的。 Here is what my model looks like:这是我的 model 的样子:

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... }所以我想要得到的结果是这样的: {'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?我的疑问是:我应该使用原始 MYSQL 查询还是应该使用 Django 的 ORM?

I tried to make it with a raw query, but didn't get the expected output:我尝试使用原始查询来实现,但没有得到预期的 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:但它给出了以下 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使用原始 mysql 或 Django ORM 进行查询没有区别,我只需要一个简单的方法来做到这一点

You should read up on how to use the function FROM_UNIXTIME() , specially the allowed format string options.您应该阅读如何使用function FROM_UNIXTIME() ,特别是允许的格式字符串选项。

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?那对你有用吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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