带有MySQL后端的Django-按时间范围分组

时间:2018-08-02 14:47:26

标签: python mysql django django-models

我有一个简单的模型:

models.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的语句?

更新:UTC 2018年8月8日星期三15:13:15

因此,我从@AKX answer获得了两种解决方案的概念证明:

models.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}'

问题:

  1. 我应该为此创建静态方法还是自定义manger是这里的正确解决方案?

  2. 如果两个计算都在内存中运行,为什么执行时间之间会有如此大的差异?有没有一种方法可以改进它并使其与python等效的方法更像pythonic?

测试:

# 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

2 个答案:

答案 0 :(得分:4)

展开我的评论:

  

我不确定即使SQL case / if语句也可以得到该结果,因为结果行取决于先前的行。不过,这很容易在Python中按程序进行。

  1. 一种明显的方法是仅循环Ping.objects.all()(或Ping.objects.iterator())并跟踪online变量以形成所需的“条纹”。这样做的缺点是您确实需要遍历每个对象,这最终会很慢(和/或耗尽您的内存)。
  2. 使用更多查询但占用更少内存的更复杂的方法是找到第一个离线的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

它是2个元组的元组的生成器:((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()

答案 1 :(得分:2)

您可以使用@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'}

正如我之前说的,您可以按照需要的方式格式化输出。