0
clicks = SellerClick.objects.extra({'date' : "date(timestamp)"}).values('date').annotate(count=Count('timestamp'))

The model has a datetime field called timestamp that was are using. I first, convert the datetime field to just a date field. Then the rest is guessing. I need to group by, and then count how many objects are of each date.

So the desired result would be a date, then a count, based on how many objects have that date in the timestamp field.

User
  • 23,729
  • 38
  • 124
  • 207

2 Answers2

3

I prefer to use annotate over extra

from django.db.models.expressions import RawSQL  

SellerClick.objects.annotate(
    date=RawSQL('date(date_joined)',[]),
).values('date').annotate(count=Count('date')))
Dean
  • 782
  • 7
  • 15
1

You've got everything but an initial queryset there. The extra sql you're passing doesn't include a select so you need to give it something to act on.

clicks = SellerClick.objects.all()
    .extra({'date' : "date(timestamp)"})
    .values('date')
    .annotate(count=Count('timestamp'))

Ref: StackOverflow: Count number of records by date in Django

Community
  • 1
  • 1
  • What if I use filter instead of `all()`? – User May 11 '16 at 03:49
  • Same principle, you'd just have to give it something to query, obviously. You could even put a select in the `.extra()` and eliminate `.all()` or `.filter()` completely, but the use case seems better lent to the way you're already doing it. – Jason Lee Eaton May 11 '16 at 03:51