Tuesday, 7 August 2018

Django with MySQL backend - group by time range

I've got this simple model:

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

It gives me the following results:

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)

Is there a way to get an output similar to this (the ranges in which online has been false):

Downtime:

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

I'm not sure if this can be done with Django ORM or it will need a raw MySQL query to use something like CASE orIF statements?



from Django with MySQL backend - group by time range

No comments:

Post a Comment