0

Currently I am developing a blog that contains articles. I wish to add the view count for the articles so that when a user views the article page, that view count will increase.

This is for my models.py file:

class Article(models.Model): 
    STATUS_CHOICES = ( 
        ('draft', 'Draft'), 
        ('published', 'Published'), 
    ) 
    title = models.CharField(max_length=250) 
    slug = models.SlugField(max_length=250,  
                            unique_for_date='publish') 
    author = models.ForeignKey(User, 
                               on_delete=models.CASCADE,
                               related_name='kbase_posts') 
    # body = models.TextField() 
    #body = RichTextField(blank=True, null=True) 
    body = RichTextField()
    publish = models.DateTimeField(default=timezone.now) 
    created = models.DateTimeField(auto_now_add=True) 
    updated = models.DateTimeField(auto_now=True) 
    status = models.CharField(max_length=10,  
                              choices=STATUS_CHOICES, 
                              default='draft') 

    objects = models.Manager() # The default manager. 
    published = PublishedManager() # Our custom manager.
    tags = TaggableManager()

    #topic = models.CharField(max_length=250, blank = True)
plebman952
  • 25
  • 2

1 Answers1

0

There are many ways to achieve this: templatetag, extending view's get method, middleware...

class Article(models.Model):
    ...
    counter = models.PositiveIntegerField(default=0)

Let's assume you want to do this in a view

from django.db.models import F

def get_article_view(request, article_id, *args, **kwagrs):
    if request.method == "GET":
        # increment counter with update method to avoid race conditions
        Article.objects.filter(id=article_id).update(counter=F('counter') + 1)
        article = Article.objects.get(id=article_id)
        return render_article(article)
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63