django和mysql后端-按时间范围分组

6g8kf2rb  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(325)

我有一个简单的模型:
型号.py

class Ping(models.Model):
    online = models.BooleanField()
    created = models.DateTimeField(db_index=True, default=timezone.now)

    def __str__(self):
        return f'{self.online}, {self.created}'

结果如下:

mysql [lab]> SELECT * FROM myapp_ping;
+----+--------+----------------------------+
| id | online | created                    |
+----+--------+----------------------------+
|  1 |      1 | 2018-08-02 13:34:09.435292 |
|  2 |      1 | 2018-08-02 13:35:09.520200 |
|  3 |      0 | 2018-08-02 13:36:09.540638 |
|  4 |      0 | 2018-08-02 13:37:10.529783 |
|  5 |      1 | 2018-08-02 13:38:09.779012 |
|  6 |      1 | 2018-08-02 13:39:09.650365 |
|  7 |      1 | 2018-08-02 13:40:09.625543 |
|  8 |      1 | 2018-08-02 13:41:09.892196 |
|  9 |      1 | 2018-08-02 13:42:09.802186 |
| 10 |      1 | 2018-08-02 13:43:09.864551 |
| 11 |      1 | 2018-08-02 13:44:09.960962 |
| 12 |      1 | 2018-08-02 13:45:09.891947 |
| 13 |      0 | 2018-08-02 13:46:09.141727 |
| 14 |      0 | 2018-08-02 13:47:09.142030 |
| 15 |      0 | 2018-08-02 13:48:09.160942 |
| 16 |      0 | 2018-08-02 13:49:09.152879 |
| 17 |      0 | 2018-08-02 13:50:09.280246 |
| 18 |      1 | 2018-08-02 13:51:09.363184 |
| 19 |      1 | 2018-08-02 13:52:09.405863 |
| 20 |      1 | 2018-08-02 13:53:09.403251 |
+----+--------+----------------------------+
20 rows in set (0.00 sec)

有没有一种方法可以得到类似的输出 online 已为假):
停机时间:

from                | to                  | duration
2018-08-02 13:36:09 | 2018-08-02 13:37:10 | 1 minute and 1 second
2018-08-02 13:46:09 | 2018-08-02 13:50:09 | 4 minutes and 0 seconds

我不确定这是否可以用django orm完成,或者它需要一个原始的mysql查询来使用 CASEIF 声明?
更新:2018年8月8日星期三15:13:15 utc
所以我从@akx answer得到了两种解决方案的概念证明:
型号.py

class PingManager(models.Manager):
    def downtime_python(self):
        queryset = super().get_queryset().filter(created__gt=timezone.now() - timezone.timedelta(days=30))
        offline = False
        ret = []
        for entry in queryset:
            if not entry.online and not offline:
                offline = True
                _ret = {'start': str(entry.created)}
            if entry.online and offline:
                _ret.update({'end': str(entry.created)})
                ret.append(_ret)
                offline = False
        return ret

    def downtime_sql(self):
        queryset = super().get_queryset().filter(created__gt=timezone.now() - timezone.timedelta(days=30))
        offline = queryset.filter(online=False).order_by('created').first()
        last = queryset.order_by('created').last()
        ret = []
        if offline:
            online = queryset.filter(created__gt=offline.created, online=True).order_by('created').first()
            ret.append({'start': str(offline.created), 'end': str(online.created)})
            while True:
                offline = queryset.filter(created__gt=online.created, online=False).order_by('created').first()
                if offline:
                    online = queryset.filter(created__gt=offline.created, online=True).order_by('created').first()
                if (online and offline) and online.created < last.created:
                    ret.append({'start': str(offline.created), 'end': str(online.created)})
                    continue
                else:
                    break
        return ret

class Ping(models.Model):
    online = models.BooleanField()
    created = models.DateTimeField(db_index=True, default=timezone.now)
    objects = PingManager()

    def __str__(self):
        return f'{self.online}, {self.created}'

问题:
我应该为此或自定义创建静态方法吗 manger 这里有正确的解决方案吗?
如果两个计算都在内存中运行,为什么执行时间会有如此巨大的差异?有没有一种方法可以改进python等效方法并使其更具python风格?
测试:


# python manage.py shell

Python 3.6.5 (default, Apr 10 2018, 17:08:37) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from myapp.models import Ping

In [2]: Ping.objects.downtime_sql()[0]
Out[2]: 
{'start': '2018-07-13 16:32:16.009356+00:00',
 'end': '2018-07-13 16:33:15.942784+00:00'}

In [3]: Ping.objects.downtime_python()[0]
Out[3]: 
{'start': '2018-07-13 16:32:16.009356+00:00',
 'end': '2018-07-13 16:33:15.942784+00:00'}

In [4]: Ping.objects.downtime_sql() == Ping.objects.downtime_python()
Out[4]: True

In [5]: import timeit

In [6]: timeit.timeit(stmt=Ping.objects.downtime_python, number=1)
Out[6]: 5.720254830084741

In [7]: timeit.timeit(stmt=Ping.objects.downtime_sql, number=1)
Out[7]: 0.25946347787976265
esyap4oy

esyap4oy1#

关于我的评论:
我不确定sql case/if语句是否能得到这个结果,因为结果行依赖于前面的行。不过,这在python中很容易按程序实现。
最明显的方法就是循环 Ping.objects.all() (或 Ping.objects.iterator() )并跟踪 online 变量来形成你想要的“条纹”。这样做的缺点是,您确实需要在每个对象上循环,这最终会很慢(和/或耗尽您的内存)。
一种更复杂的方法,即使用更多的查询,但内存要少得多,就是找到第一个 Ping 对象,然后查找下一个(按时间) Ping 再次在线的物体——会形成一条条纹。然后冲洗并重复这个直到你用完了 Ping 要检查的对象。

编辑

是的,这里有一个方法2的具体实现(相当优雅,如果你不介意我说的话)https://github.com/akx/so51656477):

class PingQuerySet(models.QuerySet):
    def streaks(self):
        queryset = self.values_list('created', 'online').order_by('created')
        entry = queryset.first()
        while entry:
            next_entry = queryset.filter(created__gt=entry[0], online=(not entry[1])).first()
            yield (entry, next_entry)
            entry = next_entry

它是两个元组的生成器: ((start_timestamp, start_online), (end_timestamp, end_online) | None) .
例如,要获取最近10天内的上/下或下/上对,

for start, end in Ping.objects.filter(created__gt=now() - timedelta(days=10)).streaks():
    print(start, end)

将打印类似

[...snip...]

(datetime.datetime(2018, 8, 8, 8, 10, 12, 943500), False) (datetime.datetime(2018, 8, 8, 10, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 8, 10, 10, 12, 943500), True) (datetime.datetime(2018, 8, 8, 11, 10, 12, 943500), False)
(datetime.datetime(2018, 8, 8, 11, 10, 12, 943500), False) (datetime.datetime(2018, 8, 8, 11, 40, 12, 943500), True)
(datetime.datetime(2018, 8, 8, 11, 40, 12, 943500), True) (datetime.datetime(2018, 8, 8, 12, 40, 12, 943500), False)
(datetime.datetime(2018, 8, 8, 12, 40, 12, 943500), False) (datetime.datetime(2018, 8, 8, 16, 40, 12, 943500), True)
(datetime.datetime(2018, 8, 8, 16, 40, 12, 943500), True) (datetime.datetime(2018, 8, 8, 17, 40, 12, 943500), False)
(datetime.datetime(2018, 8, 8, 17, 40, 12, 943500), False) (datetime.datetime(2018, 8, 8, 18, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 8, 18, 10, 12, 943500), True) (datetime.datetime(2018, 8, 8, 19, 40, 12, 943500), False)
(datetime.datetime(2018, 8, 8, 19, 40, 12, 943500), False) (datetime.datetime(2018, 8, 8, 23, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 8, 23, 10, 12, 943500), True) (datetime.datetime(2018, 8, 9, 0, 10, 12, 943500), False)
(datetime.datetime(2018, 8, 9, 0, 10, 12, 943500), False) (datetime.datetime(2018, 8, 9, 3, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 9, 3, 10, 12, 943500), True) (datetime.datetime(2018, 8, 9, 3, 40, 12, 943500), False)
(datetime.datetime(2018, 8, 9, 3, 40, 12, 943500), False) (datetime.datetime(2018, 8, 9, 5, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 9, 5, 10, 12, 943500), True) (datetime.datetime(2018, 8, 9, 5, 40, 12, 943500), False)
(datetime.datetime(2018, 8, 9, 5, 40, 12, 943500), False) (datetime.datetime(2018, 8, 9, 7, 10, 12, 943500), True)
(datetime.datetime(2018, 8, 9, 7, 10, 12, 943500), True) None

注意事项:
最后 end 值可能是 None ,表示机器仍处于上升或下降状态(取决于 start 元组)。
如果你只关心机器停机的时间,只需忽略机器停机的时间 start 元组的状态值为 True .
因为这是一个生成器,所以当您有足够的数据时,您可以停止对它的迭代,并且它不会进一步查询。
因为这是一个 QuerySet 扩展方法,您可以添加其他筛选器(只要它们不在 online ). 例如,如果你有 host 现场, Ping.objects.filter(host='example.com').streaks() .

eanckbw9

eanckbw92#

你可以使用 @classmethod 然后按照你想要的方式格式化输出,这里有一个例子:

from dateutil.relativedelta import relativedelta

class Ping(models.Model):
    online = models.BooleanField()
    created = models.DateTimeField(db_index=True, default=timezone.now)

    def __str__(self):
        return f'{self.online}, {self.created}'

    @classmethod
    def ping_online_duration(cls, is_online):
        first = cls.objects.filter(online=is_online).order_by('created').first()
        last = cls.objects.filter(online=is_online).order_by('created').last()
        return {
            'from': first.created.strftime('%Y-%m-%d %H:%M:%S'),
            'to': last.created.strftime('%Y-%m-%d %H:%M:%S'),
            'duration': (f'{relativedelta(last.created, first.created).minutes} minutes '
                         f'{relativedelta(last.created, first.created).seconds} seconds.')
        }

你可以这样称呼它:
对于联机组:

Ping.ping_online_duration(True)

{'from': '2018-08-02 15:02:19',
 'to': '2018-08-02 15:03:02',
 'duration': '0 minutes 43 seconds'}

对于离线组:

Ping.ping_online_duration(False)

{'from': '2018-08-02 15:02:27',
 'to': '2018-08-02 15:03:01',
 'duration': '0 minutes 34 seconds'}

如前所述,您可以按需要格式化输出。

相关问题