1. 利用阅读量数据排行
s2aclab/models.py
from django.contrib.contenttypes.fields import GenericRelationfrom read_statistics.models import ReadNumExpandMethod, ReadDetails...class Articles(models.Model, ReadNumExpandMethod):...read_details = GenericRelation(ReadDetails) # content_object = GenericForeignKey('content_type', 'object_id')...
read_statistics/utils.py
from s2aclab.models import Articles...# 获取一天内的热门def get_today_hot_read(content_type):today = timezone.now().date()readdetails = ReadDetails.objects.filter(content_type=content_type, date=today).order_by('-read_num')return readdetails[:5]# 获取昨天热门def get_yesterday_hot_read(content_type):yes = timezone.now().date() + timedelta(days=-1)readdetails = ReadDetails.objects.filter(content_type=content_type, date=yes).order_by('-read_num')return readdetails[:5]# 获取一周内的热门def get_one_week_hot_articles():today = timezone.now().date()date = today + timedelta(days=-6)articles = Articles.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 articles[:7]

2. 缓存数据,不用每次打开页面计算
数据库高速缓存¶
Django可以将其缓存的数据存储在您的数据库中。如果您拥有快速索引良好的数据库服务器,则此方法效果最佳。
要将数据库表用作缓存后端:
- 设置
BACKEND于django.core.cache.backends.db.DatabaseCache - 设置
LOCATION为tablename,数据库表的名称。该名称可以是您想要的任何名称,只要它是数据库中尚未使用的有效表名即可。
在此示例中,缓存表的名称为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)

