#25339: Aggregation and annotation by time period and intervals (by month, week,
day, hour, etc)
----------------------------------------------+----------------------------
     Reporter:  malefice                      |      Owner:  nobody
         Type:  New feature                   |     Status:  new
    Component:  Database layer (models, ORM)  |    Version:  1.8
     Severity:  Normal                        |   Keywords:  QuerySet.extra
 Triage Stage:  Unreviewed                    |  Has patch:  0
Easy pickings:  0                             |      UI/UX:  0
----------------------------------------------+----------------------------
 I often found that aggregation of data by dynamically generating time
 periods given a desired time interval is a very sought after feature. I
 personally created the snippet below to accommodate my needs, but as per
 the note
 
[https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra
 here], the extra() method will be deprecated soon. I think it will be a
 waste to deprecate this API, since there is simply a lot of DBMS-specific
 SQL functions available, but if there is any way we can do this via Django
 ORM, then I am still up for it. The snippet below shows a custom QuerySet
 method I often use.

 {{{#!python
 def get_metrics(self, frequency):
     select_fields = OrderedDict()
     if frequency == 'week':
         select_fields['time_period'] = "date_trunc(%s,
 initial_timestamp::TIMESTAMP WITH TIME ZONE AT TIME ZONE %s + '1
 day'::interval) - '1 day'::interval"
     else:
         select_fields['time_period'] = "date_trunc(%s,
 initial_timestamp::TIMESTAMP WITH TIME ZONE AT TIME ZONE %s)"
     select_params = (frequency, settings.TIME_ZONE,)
     queryset = self.extra(select=select_fields,
 select_params=select_params).values('time_period', ....)
     queryset = queryset.annotate(
         # Add annotations
     )
     return queryset
 }}}

--
Ticket URL: <https://code.djangoproject.com/ticket/25339>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/051.f1d06a27fd67e6b76085f3eb238b14d9%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to