John
John

Reputation: 31

Django View Counter

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})

Upvotes: 2

Views: 6307

Answers (2)

manish adwani
manish adwani

Reputation: 24

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!

Upvotes: -1

catavaran
catavaran

Reputation: 45595

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

Upvotes: 12

Related Questions