Django GROUP BY strftime date format

Andrew C picture Andrew C · Apr 6, 2009 · Viewed 9.8k times · Source

I would like to do a SUM on rows in a database and group by date.

I am trying to run this SQL query using Django aggregates and annotations:

select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
    from my_model
    group by the_date;

I tried the following:

data = My_Model.objects.values("strftime('%m/%d/%Y',
           time_stamp)").annotate(Sum("numbers_data")).order_by()

but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().

How should I go about this?

Answer

Andrew C picture Andrew C · Apr 6, 2009

This works for me:

select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""}

data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by()

Took a bit to figure out I had to escape the % signs.