如何在Django ORM中对datetime字段进行group by查询?在
型号:class test1(models.Model):
id = models.AutoField(primary_key=True, unique=True, verbose_name='id')
name = models.CharField(verbose_name='name', max_length=200)
cdate = models.DateField(verbose_name='date', default=timezone.now)
查询集数据
^{pr2}$
需要按月分组并用Django orm计算id。在
奎里塞特data = test1.objects.annotate(month=TruncMonth('cdate')).values('month').annotate(c=Count('id'))
for i in data:
print i
结果{'c': 1, 'month': datetime.date(2017, 8, 1)}
{'c': 1, 'month': datetime.date(2017, 8, 1)}
{'c': 1, 'month': datetime.date(2017, 8, 1)}
{'c': 1, 'month': datetime.date(2017, 8, 1)}
{'c': 1, 'month': datetime.date(2017, 8, 1)}
为什么不呢?在{'c': 5, 'month': datetime.date(2017, 8, 1)}