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