How to group by queryset on datetime field in Django ORM?
models:
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)
queryset data
for i in test1.objects.all():
print i.id, i.name, i.cdate
2 a 2017-08-11
3 b 2017-08-11
4 c 2017-08-11
5 a 2017-08-11
6 a 2017-08-11
need group by month and count IDs with Django orm.
queryset
data = test1.objects.annotate(month=TruncMonth('cdate')).values('month').annotate(c=Count('id'))
for i in data:
print i
result
{'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)}
why not?
{'c': 5, 'month': datetime.date(2017, 8, 1)}