[Django學習] Django基礎(12)_熱門博客排行

一. 博客閱讀次數排行

  博客被閱讀的次數越多,表明該博客越熱門。一般按照時間的長短來進行分類統計: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

三. 具體思路

1. 獲取今日的時間

today = timezone.now().date()

2. 計算出要分類的時間

date = today-datetime.timedelta(days=daynum)

3. 在blog.models.Blog中添加contenttypes.field.GenericRelation

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)    
        # ...其餘內容神略

4. 獲取時間條件內全部博客

# 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>>]>

5. 提取具體博客的id和title(使用QuerySet中的values()方法)

>>> 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'}]>

6. 對查詢出的QuerySet進行統計(使用QuerySet中的annotate()方法)

>>> 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}]>

7. 封裝成方法

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]

8. views.py中調用該方法

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

相關文章
相關標籤/搜索