mysql - Django group by dates and SUM values -


this question has answer here:

is possible reproduce following mysql query in django without using select method ?

mariadb [db1]> select datetime, sum(datas) table , datetime between '2013-07-26 13:00:00' , '2013-07-26 23:00:00' group datetime; 

to kind of result :

+---------------------+-----------+ | datetime            | sum(data) | +---------------------+-----------+ | 2013-07-26 13:00:00 |       489 | | 2013-07-26 14:00:00 |      2923 | | 2013-07-26 15:00:00 |       984 | | 2013-07-26 16:00:00 |      2795 | | 2013-07-26 17:00:00 |      1308 | | 2013-07-26 18:00:00 |      1365 | | 2013-07-26 19:00:00 |      1331 | | 2013-07-26 20:00:00 |       914 | | 2013-07-26 21:00:00 |       919 | | 2013-07-26 22:00:00 |       722 | | 2013-07-26 23:00:00 |       731 | +---------------------+-----------+ 11 rows in set (1.45 sec) 

edit: got kind of query :

>>> value = table.objects.filter(datetime__range=('2013-07-26 13:00:00',   '2013-07-26 23:00:00')).values('datetime', 'data').annotate(sum('data'))  >>> print value.query select `table`.`datetime`, `table`.`data` sum(`table`.`imps`) `data__sum`  `table` `table`.`datetime` between 2013-07-26 13:00:00 , 2013-07-26 23:00:00 group `table`.`datetime`, `table`.`data` order null 

why sum operate on both datetime , data?

i tried everywhere on django doc, here on stack didn't find coherent problem. suggestion ?

hmm using count, should use sum, , values() determine goes group by should use values('datetime') only. queryset should this:

from django.db.models import sum  values = self.model.objects.filter(     datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').annotate(data_sum=sum('data')) 

although i'm not sure order of filter(), this:

values = self.model.objects.values('datetime').annotate(data_sum=sum('data')).filter(     datetime__range=(self.dates[0], self.dates[1]) ) 

i guess wanna try both then. if want see raw query of queryset, use queryset.query:

print self.model.objects.filter(     datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').annotate(data_sum=sum('data')).query.__str__() 

so can make sure right query.

hope helps.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -