User
User

Reputation: 24731

Group objects by dates

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.

Upvotes: 0

Views: 1273

Answers (2)

Dean
Dean

Reputation: 948

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')))

Upvotes: 3

Jason Lee Eaton
Jason Lee Eaton

Reputation: 178

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

Upvotes: 1

Related Questions