tags:

views:

296

answers:

1

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)
+5  A: 

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.

Daniel Roseman
thanks, getting this error"Caught an exception while rendering: zip argument #2 must support iteration" with template as: {% for key, value in counts %}{{ key }}: {{ value }}{% endfor %}"
bocca
try `{% for key, value in counts.items %}`
Daniel Roseman
getting "Caught an exception while rendering: 'int' object is not iterable" is this is in view okay for dictionary: return render_to_response('page.html', {'counts': counts}, context_instance=RequestContext(request) )
bocca