2

What is the best way to make view counter function in my views.py ?

I did find F() expressions in Django documentation , but how to make it work or any better idea?

Thank you in advance

def watch_video(request, slug):

    video = get_object_or_404(Video, slug=slug)

    template = "single_video.html" 

    #if this function will run , + 1 in Video.views ?


    return render(request,template,{"video":video})

my model:

class Video(models.Model):

    video_id = models.CharField(max_length=150)
    title = models.CharField(max_length=150)
    slug = AutoSlugField(populate_from="title")
    description = models.TextField(blank=True)
    views = models.PositiveIntegerField(default=0)
    likes = models.PositiveIntegerField(default=0)
    category = models.ForeignKey("VideoCategory")
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    tags = models.ManyToManyField("Tag")


    def __str__(self):

        return self.title

    def get_absolute_url(self):

        return reverse("watch", kwargs={"slug" : self.slug})
John
  • 31
  • 1
  • 4
  • 2
    You don't just want to increment counter on every visit from same IP. You need to track IP so that if user visits from same IP again and again the counter should not Increment. There are some packsges out there such as [django-hitcount](https://github.com/thornomad/django-hitcount/) and [django-visits](https://bitbucket.org/jespino/django-visits) – Aamir Rind Mar 03 '15 at 13:35
  • Possible duplicate of [Track the number of "page views" or "hits" of an object?](https://stackoverflow.com/questions/1603340/track-the-number-of-page-views-or-hits-of-an-object) – Sardorbek Imomaliev Aug 06 '19 at 04:10

2 Answers2

12

Call the update() on the queryset which filters the single video:

from django.db.models import F

Video.objects.filter(pk=video.pk).update(views=F('views') + 1)
video.views += 1 # to show valid counter in the template
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • That's generally the right way to do it. the only thing I'd change is the way you add to the object you currently have. it's better to reload the video from the database (or load it only after the update). for the first option you should use video.refresh_from_db(fields=['views']) - this is because this field might be updated by other viewers while this is running – Mr. Nun. Jan 26 '17 at 18:13
-1

It's very simple make an increase function in model which increment views by 1

Then in views.py call that increase function everytime a user visits that model's page and save it!

manish adwani
  • 24
  • 1
  • 7