11

I have a Django model with a created timestamp and I'd like to get the counts of objects created on each day. I was hoping to use the aggregation functionality in Django but I can't figure out how to solve my problem with it. Assuming that doesn't work I can always fall back to just getting all of the dates with values_list but I'd prefer to give the work to Django or the DB. How would you do it?

guidoism
  • 7,820
  • 8
  • 41
  • 59

2 Answers2

25

Alex pointed to the right answer in the comment:

Count number of records by date in Django
Credit goes to ara818

Guidoism.objects.extra({'created':"date(created)"}).values('created').annotate(created_count=Count('id'))

from django.db.models import Count

Guidoism.objects \
    # get specific dates (not hours for example) and store in "created" 
    .extra({'created':"date(created)"})
    # get a values list of only "created" defined earlier
    .values('created')
    # annotate each day by Count of Guidoism objects
    .annotate(created_count=Count('id'))

I learn new tricks every day reading stack.. awesome!

Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • `extra` is listed as deprecated soon. Try `TruncDay` instead now https://stackoverflow.com/a/8746532/2283261 – nwself Sep 09 '20 at 19:08
0

Use the count method:

YourModel.objects.filter(published_on=datetime.date(2011, 4, 1)).count()
crodjer
  • 13,384
  • 9
  • 38
  • 52