0

I have this queryset function to count the field created but I would love to count by day and not how it is currently because I want to make chart with this data.

           queryset = Model.objects.filter(
            user=user
        ).values("created").annotate(
            Count("created")).order_by("created")

Result:

 [{"created__count": 1, "created": "2013-10-01T09:05:50Z"}, {"created__count": 1, "created": "2013-10-01T09:05:53Z"}, {"created__count": 1, "created": "2013-10-01T09:05:56Z"}, {"created__count": 1, "created": "2013-10-01T09:26:37Z"}, {"created__count": 1, "created": "2013-10-01T09:26:41Z"}, {"created__count": 1, "created": "2013-10-01T09:27:10Z"}, {"created__count": 1, "created": "2013-10-01T09:27:15Z"}, {"created__count": 1, "created": "2013-10-01T10:12:40Z"}, {"created__count": 1, "created": "2013-10-01T10:12:46Z"}, {"created__count": 1, "created": "2013-10-01T10:12:53Z"}]

This there some way to count by day like 11/11: Count 20, 12/11: Count 22.

Should I compute this data after I got it from the queryset?

Johan
  • 74,508
  • 24
  • 191
  • 319
Azd325
  • 5,752
  • 5
  • 34
  • 57

1 Answers1

1

You should try Count('created__day'). At least created__day should work in the filtering part of the query, so intuitively, it should also work with Count.

EDIT:

...nope, it doesn't work, but you might find a solution in Count number of records by date in Django.

So basically you have to use .extra(...) combined with some (potentially non-standard) SQL functions that extract just a part of a datetime (e.g. the MySQL DATE()), and then use the resulting field to Count.

Community
  • 1
  • 1
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111