Add a views count on article
Incremented by non logged in visitors
This commit is contained in:
parent
0c1d0a0b29
commit
7ab0f6ee24
4 changed files with 32 additions and 4 deletions
|
@ -26,12 +26,12 @@ class ArticleAdmin(admin.ModelAdmin):
|
||||||
{
|
{
|
||||||
"fields": (
|
"fields": (
|
||||||
"title",
|
"title",
|
||||||
"status",
|
("author", "status"),
|
||||||
("created_at", "published_at", "updated_at"),
|
("published_at", "created_at", "updated_at"),
|
||||||
"author",
|
"views_count",
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
("Content", {"fields": ("content",)}),
|
("Content", {"fields": ("content",)}),
|
||||||
]
|
]
|
||||||
readonly_fields = ["created_at", "updated_at"]
|
readonly_fields = ["created_at", "updated_at", "views_count"]
|
||||||
|
|
18
articles/migrations/0004_article_views_count.py
Normal file
18
articles/migrations/0004_article_views_count.py
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
# Generated by Django 3.1 on 2020-08-14 20:03
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("articles", "0003_auto_20200814_1522"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="article",
|
||||||
|
name="views_count",
|
||||||
|
field=models.IntegerField(default=0),
|
||||||
|
),
|
||||||
|
]
|
|
@ -23,6 +23,7 @@ class Article(models.Model):
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
updated_at = models.DateTimeField(auto_now=True)
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
author = models.ForeignKey(User, on_delete=models.PROTECT)
|
author = models.ForeignKey(User, on_delete=models.PROTECT)
|
||||||
|
views_count = models.IntegerField(default=0)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ["-published_at"]
|
ordering = ["-published_at"]
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from django.db.models import F
|
||||||
from django.views import generic
|
from django.views import generic
|
||||||
|
|
||||||
from articles.models import Article
|
from articles.models import Article
|
||||||
|
@ -18,3 +19,11 @@ class ArticleDetailView(generic.DetailView):
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
return super().get_queryset().filter(status=Article.PUBLISHED)
|
return super().get_queryset().filter(status=Article.PUBLISHED)
|
||||||
|
|
||||||
|
def get_object(self, queryset=None):
|
||||||
|
obj = super().get_object(queryset)
|
||||||
|
if not self.request.user.is_authenticated:
|
||||||
|
obj.views_count = F("views_count") + 1
|
||||||
|
obj.save(update_fields=["views_count"])
|
||||||
|
|
||||||
|
return obj
|
||||||
|
|
Reference in a new issue