在阅读计数功能之后,就可以可根据每篇博客的阅读量来对博客进行热门统计排行了,如阅读周榜,月榜,总榜。基本上只要实现其中一个,其他两个也能照着做出来,大体上的逻辑是一样的。都是通过django自带的工具包中的timezone模块获取今天的日期格式,再通过datetime模块的timedelta方法来做日期的差值,然后筛选出这两个时间点之间发表的文章,除了总榜只需要筛选出日期小于今天发表的文章。将该时间段的博客列表筛选出来之后,通过聚合函数求出每篇文章的阅读量总和,然后进行阅读量的排序
1.周榜
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.月榜
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.最新发表
from blog.models import Post
new_publish = Post.objects.all()[:15]
5.最新推荐
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.随机推荐
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