博客被閱讀的次數越多,表明該博客越熱門。一般按照時間的長短來進行分類統計:html
1. 今日熱門python
2. 七天熱門django
3. 三十天熱門學習
具體html代碼(以今天熱門點擊爲例)爲:url
<!-- 24小時之內熱帖 --> <h3>今天熱門點擊</h3> <ul> {% for hot_data in today_hot_data %} <li><a href="{% url 'blog_detail' hot_data.id %}">{{ hot_data.title }}</a>({{hot_data.read_num_sum}})</li> {% empty %} <li>今天暫時沒有熱門博客</li> {% endfor %} </ul>
從代碼中可知,須要具體某一片博客的id(hot_data.id),title(hot_data.title)以及該博客的閱讀計數統計(hot_data.read_num_sum)。spa
today = timezone.now().date()
date = today-datetime.timedelta(days=daynum)
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation from blogstatistics.models import ReadNum,ReadNumExpandMethod, ReadDetailNum from ckeditor_uploader.fields import RichTextUploadingField class Blog(models.Model, ReadNumExpandMethod): # ...其餘內容省略 # GenericRelation:能夠讓Blog使用與其指定關聯的ReadDtailNum中的內容 read_details = GenericRelation(ReadDetailNum) # ...其餘內容神略
# blog.models.Blog中的read_details=GenericRelation(ReadDetailNum) # Blog能夠使用ReadDetailNum中的date屬性 >>> blogs = Blog.objects.filter(read_details__date__lte=today,read_details__date__gte=sevendate) >>> blogs <QuerySet [<Blog: <BLog: for 29>>, <Blog: <BLog: for 27>>, <Blog: <BLog: for 26>>, <Blog: <BLog: for 24>>, <Blog: <BLog: for 24>>]>
>>> blogs.values('id','title') <QuerySet [{'id': 32, 'title': 'for 29'}, {'id': 30, 'title': 'for 27'}, {'id': 29, 'title': 'for 26'}, {'id': 27, 'title': 'for 24'}, {'id': 27, 'title': 'for 24'}]>
>>> from django.db.models import Sum #一樣,BGenericRelation讓涉及Blog的全部對象均可以使用ReadDetailNum中的字段 >>> blogs.values('id','title').annotate(Sum('read_details__read_num')) <QuerySet [ {'id': 32, 'title': 'for 29', 'read_details__read_num__sum': 1}, {'id': 30, 'title': 'for 27', 'read_details__read_num__sum': 1}, {'id': 29, 'title': 'for 26', 'read_details__read_num__sum': 1}, {'id': 27, 'title': 'for 24', 'read_details__read_num__sum': 4}]>
def get_blogs_hot_data(daynum): today = timezone.now().date() date = today-datetime.timedelta(days=daynum) blogs = Blog.objects \ .filter(read_details__date__lte=today, read_details__date__gte=date) \ .values('id', 'title') \ .annotate(read_num_sum=Sum('read_details__read_num')) \ .order_by('-read_num_sum') return blogs[:7]
from django.shortcuts import render_to_response from django.contrib.contenttypes.models import ContentType from blogstatistics.utils import get_seven_days_read_data, get_blogs_hot_data from blog.models import Blog def home(request): ct = ContentType.objects.get_for_model(Blog) date_list,read_nums = get_seven_days_read_data(ct) context = {} context['date_list']=date_list context['read_nums'] = read_nums context['today_hot_data'] = get_blogs_hot_data(0) context['sevenday_hot_data'] = get_blogs_hot_data(7) context['month_hot_data'] = get_blogs_hot_data(30) return render_to_response('home.html',context)
註明:學習資料來自「再敲一行代碼的我的空間」以及「楊仕航的博客」code