django aggregation to lower resolution using grouping by a date range

后端 未结 4 718
南旧
南旧 2021-01-05 07:18

horrible title, but let me explain: i\'ve got this django model containing a timestamp (date) and the attribute to log - f.e. the number of users consuming some ressource -

4条回答
  •  不知归路
    2021-01-05 08:11

    I've been trying to solve this problem in the most 'django' way possible. I've settled for the following. It averages the values for 15minute time slots between start_date and end_date where the column name is'date':

    readings = Reading.objects.filter(date__range=(start_date, end_date)) \
       .extra(select={'date_slice': "FLOOR (EXTRACT (EPOCH FROM date) / '900' )"}) \
       .values('date_slice') \
       .annotate(value_avg=Avg('value'))
    

    It returns a dictionary:

     {'value_avg': 1116.4925373134329, 'date_slice': 1546512.0}
     {'value_avg': 1001.2028985507246, 'date_slice': 1546513.0}
     {'value_avg': 1180.6285714285714, 'date_slice': 1546514.0}
    

    The core of the idea comes from this answer to the same question for PHP/SQL. The code passed to extra is for a Postgres DB.

提交回复
热议问题