文章浏览量是所有社交类网站所必备的数据,足以显示其重要性了。
博主可以通过浏览量来评估某篇文章的受欢迎程度,读者也能够通过浏览量来筛选质量更高的文章。
然而,准确统计浏览量并不简单:
- 某些类型的请求不应该统计为浏览量,比如作者自己的浏览或编辑文章之后的重定向请求;
- 由于用户众多,浏览量的数据时刻都在快速更新,会给数据库带来很大的压力。因此很多大型网站都会使用如Redis这样的读写速度非常快的内存数据库辅助存储。
因为我们的项目是博客网站,粗略统计就可以了,也没有那么大的用户压力,所以设计就简单得多了。
模型
浏览量作为每篇博文都有的数据,需要一个字段来存储。
因此修改文章的模型:
article/models.py
...
class ArticlePost(models.Model):
...
total_views = models.PositiveIntegerField(default=0)
...
PositiveIntegerField
是用于存储正整数的字段default=0
设定初始值从0开始
修改完数据库别忘了要数据迁移,否则更改不会生效。
由于新字段设置了初始值,迁移会很顺畅:
(env) E:\django_project\my_blog>python manage.py makemigrations
Migrations for 'article':
article\migrations\0003_articlepost_total_views.py
- Add field total_views to articlepost
Migrations for 'userprofile':
userprofile\migrations\0002_auto_20181227_2041.py
- Alter field avatar on profile
- Alter field user on profile
(env) E:\django_project\my_blog>python manage.py migrate
Operations to perform:
Apply all migrations: admin, article, auth, contenttypes, sessions, userprofile
Running migrations:
Applying article.0003_articlepost_total_views... OK
Applying userprofile.0002_auto_20181227_2041... OK