我有一个帖子模型,尝试正确实现视图计数器,但是当我尝试在模板中显示视图计数器时,此方法在模板中无法正常工作。

    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解决吗?

最佳答案

问题是您使用F表达式来增加视图计数器,但是必须重新加载该对象才能使它获取新值。您可以为此使用refresh_from_db()

def count_views(self):
    self.views = F('views') + 1
    self.save()
    self.refresh_from_db()


不重新加载,self.views的值将是F()表达式的字符串表示形式,这是您当前在模板中看到的内容。

关于python - 如何在模板中正确显示递增的Django模型字段值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50870950/

10-11 23:37