个人网站搭建 (第九天) 博客统计排行

    在阅读计数功能以后,就能够可根据每篇博客的阅读量来对博客进行热门统计排行了,如阅读周榜,月榜,总榜。基本上只要实现其中一个,其余两个也能照着作出来,大致上的逻辑是同样的。都是经过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
相关文章
相关标签/搜索