Django last 30 listings

With a model like in Django, how to get 30-day entries with a count of the amount added on that day.

class Entry(models.Model):
    ...
    entered = models.DateTimeField(auto_now_add=True)
+3
source share
1 answer

Getting the last 30 days of recordings is easy:

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

Counting the amount every day is much more complicated because you store timestamps, not days - if you used DateField, you could just do a simple aggregation. Perhaps the best thing you can do is to sort 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- a dictionary whose keys are the number of days until today, and the values ​​are the number of entries on that day.

+11
source

Source: https://habr.com/ru/post/1727089/


All Articles