bocca
bocca

Reputation: 1995

django last 30 entry list with count

With a model like this in Django, how to retrive 30 days entries with count how many were added on that day.

class Entry(models.Model):
    ...
    entered = models.DateTimeField(auto_now_add=True)

Upvotes: 2

Views: 2528

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599638

Getting the last 30 days entries is easy:

today = datetime.date.today()
thirty_days_ago = today - datetime.timedelta(days=30)
entries = Entry.objects.filter(entered__gte=thirty_days_ago)

Counting how many on each day is much trickier, because you're storing timestamps, not days - if you were using a DateField you could just do a simple aggregation. Perhaps the best thing to do is iterate through and count them per day:

from collections import defaultdict
counts = defaultdict(int)
for entry in entries.order_by('entered'):
    date = entry.entered.date()
    days = (today - date).days
    counts[days] += 1

Now counts is a dictionary whose keys are the number of days before today, and the values are the number of entries on that day.

Upvotes: 12

Related Questions