我有一个帖子模型,并试图实现正确的视图计数器,但当我尝试在模板中显示视图计数器时,此方法在模板中无法正常工作。
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
title = models.CharField(max_length=160)
slug = models.SlugField(null=True, blank=True, max_length=160)
content = models.TextField()
created = models.DateTimeField(default=datetime.datetime.now, blank=True)
updated = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='news/photos/', default='', blank=True)
views = models.PositiveIntegerField(default=0)
class Meta:
verbose_name = 'Post'
verbose_name_plural = 'News'
ordering = ['id']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
return super(Post, self).save(*args, **kwargs)
def count_views(self):
self.views = F('views') + 1
self.save()
class PostDetail(DetailView):
model = Post
template_name = 'news/detail.html'
def get_context_data(self, **kwargs):
context = super(PostDetail, self).get_context_data(**kwargs)
self.object.count_views()
context['latest_news'] = Post.objects.all().order_by('-created')[0:10]
return context
<span><i class="icon-eye icons"></i> {{ post.views }}</span>
可能有另一种方法可以解决这个问题,更正确。我能用.update queryset解决这个问题吗?
答案 0 :(得分:0)
问题是您使用F
表达式来递增视图计数器,但必须重新加载该对象才能获取新值。您可以使用refresh_from_db()
。
def count_views(self):
self.views = F('views') + 1
self.save()
self.refresh_from_db()
如果不重新加载,self.views
的值将是F()
表达式的字符串表示形式,这是您目前在模板中看到的内容。