[Answer]-Django order_by last week days

1👍

Calculate the last week week range and you can use date range query. For example.

import datetime
from django.db.models import Count

from_date = datetime.datetime.now() - datetime.timedelta(days=7)

click_info.objects.filter(hash='<value>', created_at__range=[from_date, datetime.datetime.now()])
    .extra({'date_created' : "date(created_at)"})
    .values('date_created')
    .annotate(created_count=Count('id'))

It will give a list of dict elements. You can manipulate further based on your purpose.

[{'date_created': u'2013-09-03', 'created_count': 1}, 
 {'date_created': u'2013-09-04', 'created_count': 1}, 
 {'date_created': u'2013-09-05', 'created_count': 1}, 
 {'date_created': u'2013-09-06', 'created_count': 3}, 
 {'date_created': u'2013-09-07', 'created_count': 1}, 
 {'date_created': u'2013-09-08', 'created_count': 1}, 
 {'date_created': u'2013-09-09', 'created_count': 2}]

You can use the below snippet to strip the day and count.

day_clicks = []
for item in items:
    day = datetime.datetime.strptime(item.get('date_created'), "%Y-%m-%d").date().strftime("%a")
    click_count = item.get('created_count')
    day_clicks.append(day + ':' + str(click_count))
print ", ".join(day_clicks)

Result:

Tue:1, Wed:1, Thu:1, Fri:3, Sat:1, Sun:1, Mon:2

0👍

import datetime

now = datetime.datetime.now()
last_week = now - datetime.timedelta(days=7)

short_url.objects \
         .filter(click_info__created_at__range=[last_week,now]) \
         .annotate(click_count=Count('click_info'))

Leave a comment