在閱讀計數功能以後,就能夠可根據每篇博客的閱讀量來對博客進行熱門統計排行了,如閱讀周榜,月榜,總榜。基本上只要實現其中一個,其餘兩個也能照着作出來,大致上的邏輯是同樣的。都是經過django自帶的工具包中的timezone模塊獲取今天的日期格式,再經過datetime模塊的timedelta方法來作日期的差值,而後篩選出這兩個時間點之間發表的文章,除了總榜只須要篩選出日期小於今天發表的文章。將該時間段的博客列表篩選出來以後,經過聚合函數求出每篇文章的閱讀量總和,而後進行閱讀量的排序python
1.周榜django
import datetime from django.utils import timezone from django.db.models import Sum from blog.models import Post def get_7_days_read_posts(): """ 做用:獲取閱讀量周榜博客榜單 """ today = timezone.now().date() date = today - datetime.timedelta(days=7) posts = Post.objects \ .filter(read_detail__date__lt=today, read_detail__date__gte=date) \ .values('id', 'title') \ .annotate(read_num_sum=Sum('read_detail__read_num')) \ .order_by('-read_num_sum') return posts[:15]
2.月榜dom
import datetime from django.utils import timezone from django.db.models import Sum from blog.models import Post def get_30_days_read_posts(): """ 做用:獲取閱讀量月榜博客榜單 """ today = timezone.now().date() date = today - datetime.timedelta(days=30) posts = Post.objects \ .filter(read_detail__date__lt=today, read_detail__date__gte=date) \ .values('id', 'title') \ .annotate(read_num_sum=Sum('read_detail__read_num')) \ .order_by('-read_num_sum') return posts[:15]
3.總榜函數
import datetime from django.utils import timezone from django.db.models import Sum from blog.models import Post def get_all_read_posts(): """ 做用:獲取閱讀量總榜博客榜單 """ today = timezone.now().date() posts = Post.objects \ .filter(read_detail__date__lt=today) \ .values('id', 'title') \ .annotate(read_num_sum=Sum('read_detail__read_num')) \ .order_by('-read_num_sum') return posts[:15]
在首頁視圖中,還有最新發表的博客,最新推薦的博客和隨機推薦的博客,他們的實現以下:工具
4.最新發表post
from blog.models import Post new_publish = Post.objects.all()[:15]
5.最新推薦code
import datetime from django.utils import timezone from .models import ReadDetail def get_new_recommend_post(content_type): """ 做用:獲取最新推薦博客列表 content_type:數據表的模型類 """ today = timezone.now().date() yesterday = today - datetime.timedelta(days=1) read_detail = ReadDetail.objects.filter(content_type=content_type, date=yesterday).order_by('-read_num') return read_detail[0:15] # 前十五條
6.隨機推薦blog
import random from blog.models import Post def get_random_recomment(): # 隨機推薦 random_posts = set() post_list = Post.objects.all() while random_posts.__len__() < 15: random_posts.add(random.choice(post_list)) return random_posts