在views.py中制作视图计数器功能的最佳方法是什么?
我确实在Django文档中找到了F()表达式,但是如何让它工作或者更好的想法?
提前谢谢
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})
我的模特:
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})
答案 0 :(得分:6)
调用查询集上的update()
,过滤单个视频:
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
答案 1 :(得分:0)
在模型中增加函数非常简单,将视图递增1
然后在views.py中调用每次用户访问该模型页面时增加功能并保存它!