models.py
class short_url(models.Model):
"""
This is a short_url class
"""
blocked = models.BooleanField(default=False) # To check whether URL is blocked or not
updated_at = models.DateTimeField(auto_now=True) # When URL is updated
url = models.TextField(validators=[URLValidator()]) # URL entered by the user
created_at = models.DateTimeField(auto_now_add=True) # When URL is created
url_hash = models.CharField(max_length=10,unique=True,db_index=True) # base64 encoded URL id
class click_info(models.Model):
"""
This is a click_info class
"""
user_ip = models.TextField() # Store the user_ip
user_agent = models.TextField() # Store the user_agent
http_refrer = models.TextField() # Store the http_refrer
hash = models.ForeignKey(short_url) # base64 encoded URL id
get_parameters = models.TextField() # Store other get_parameters
request_time = models.DateTimeField() # When user made the request_time
updated_at = models.DateTimeField(auto_now=True) # When click_info is updated
created_at = models.DateTimeField(auto_now_add=True) # When click is created
以上是我的两个模型。我想获得上周特定url_hash的总点击次数。例如,如果今天进行查询,那么它应该仅返回过去工作日的数据...
Mon:2,Tue:1,Wed:10,Thu:122,Fri:97,Sat:12,Sun:11
答案 0 :(得分:1)
计算上周工作周范围,您可以使用日期范围查询。例如。
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'))
它将给出一个dict元素列表。您可以根据自己的目的进一步操纵。
[{'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}]
您可以使用以下代码段去除日期并计算。
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)
<强>结果:强>
Tue:1, Wed:1, Thu:1, Fri:3, Sat:1, Sun:1, Mon:2
答案 1 :(得分: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'))