1. 利用阅读量数据排行

17 热门博文排行和缓存提速 - 图1 s2aclab/models.py

  1. from django.contrib.contenttypes.fields import GenericRelation
  2. from read_statistics.models import ReadNumExpandMethod, ReadDetails
  3. ...
  4. class Articles(models.Model, ReadNumExpandMethod):
  5. ...
  6. read_details = GenericRelation(ReadDetails) # content_object = GenericForeignKey('content_type', 'object_id')
  7. ...

read_statistics/utils.py

  1. from s2aclab.models import Articles
  2. ...
  3. # 获取一天内的热门
  4. def get_today_hot_read(content_type):
  5. today = timezone.now().date()
  6. readdetails = ReadDetails.objects.filter(content_type=content_type, date=today).order_by('-read_num')
  7. return readdetails[:5]
  8. # 获取昨天热门
  9. def get_yesterday_hot_read(content_type):
  10. yes = timezone.now().date() + timedelta(days=-1)
  11. readdetails = ReadDetails.objects.filter(
  12. content_type=content_type, date=yes).order_by('-read_num')
  13. return readdetails[:5]
  14. # 获取一周内的热门
  15. def get_one_week_hot_articles():
  16. today = timezone.now().date()
  17. date = today + timedelta(days=-6)
  18. articles = Articles.objects.filter(
  19. read_details__date__lte=today,read_details__date__gte=date
  20. ).values('id', 'title').annotate(read_num_sum=Sum('read_details__read_num')).order_by('-read_num_sum')
  21. return articles[:7]

17 热门博文排行和缓存提速 - 图2

2. 缓存数据,不用每次打开页面计算

数据库高速缓存

Django可以将其缓存的数据存储在您的数据库中。如果您拥有快速索引良好的数据库服务器,则此方法效果最佳。

要将数据库表用作缓存后端:

  • 设置BACKENDdjango.core.cache.backends.db.DatabaseCache
  • 设置LOCATIONtablename,数据库表的名称。该名称可以是您想要的任何名称,只要它是数据库中尚未使用的有效表名即可。

在此示例中,缓存表的名称为my_cache_table

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

创建缓存表

在使用数据库缓存之前,必须使用以下命令创建缓存表:

python manage.py createcachetable

这会在您的数据库中创建一个表,该表的格式与Django的数据库缓存系统期望的格式相同。该表的名称取自 LOCATION

project/views.py

from read_statistics.utils import get_one_week_read_statistics, get_today_hot_read, get_yesterday_hot_read, get_one_week_hot_articles
from django.core.cache import cache
...

def home(request):
    content_type = ContentType.objects.get_for_model(Articles)
    read_sum, dates = get_one_week_read_statistics(content_type)

    # 一周热门
    week_hot = cache.get('week_hot')
    if not week_hot:
        week_hot = get_one_week_hot_articles()
        cache.set('week_hot', week_hot, 3600)  #   3600s
        print('calculate')
    else:
        print('use cache')

    context = {}
    context['read_sum'] = read_sum
    context['dates'] = dates
    context['today_hot'] = get_today_hot_read(content_type)
    context['yesterday_hot'] = get_yesterday_hot_read(content_type)
    context['week_hot'] = week_hot
    return render(request,'home.html',context)

17 热门博文排行和缓存提速 - 图3