Django框架models使用group by的方法:
首先,看下列代码:
UserData.objects.filter(hubid=sensorid,time__range=(time2,time1)).values('hour').annotate(sum_out=Sum('outdoor'), sum_in=Sum('indoor'), sum_eat=Sum('kitchen'), sum_wash=Sum('toilet')).order_by('hour')
上述代码相当于sql语句:
select Sum('outdoor') as sum_out,Sum('indoor') as sum_in,Sum('kitchen') as sum_eat,Sum('toilet') as sum_wash,hour
where hubid='sensorid' and (time between time1 and time2)
group by hour
order by hour asc
另外,在Django中order_by(‘hour’)表示按生序排列,若要按降序排列,则使用order_by(‘-hour’)
版权声明:本文为tianweitao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。