修复django views counter

时间:2017-09-30 17:23:37

标签: django session-cookies

我正在使用 Django 创建博客,我想计算每个帖子的观看次数。当用户阅读博客帖子时,我会调用此函数:

def post_detail(request, post_id):
    if 'viewed_post_%s' % post_id in request.session:
        pass
    else:
        print "adding"
        add_view = Post.objects.get(id=post_id)
        add_view.views += 1
        add_view.save()
    request.session['viewed_post_%s' % post_id] = True
    return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)})

问题是,当注销并再次登录时,帖子视图会再次增加。那么为什么django会在用户注销时删除会话以及如何解决这个问题呢?

2 个答案:

答案 0 :(得分:1)

您不能依赖会话来存储此类永久信息,因为sessions是临时的。

最简单的方法是添加其他模型:

class UserSeenPosts(models.Model):
    user = models.ForeignKey(User, related_name='seen_posts')
    post = models.ForeignKey(Post)

然后做这样的事情:

def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)

    if not request.user.seen_posts.filter(post_id=post_id).exists():
        print "adding"
        post.views += 1
        post.save()
        UserSeenPosts.objects.create(user=request.user, post=post)            

    return render(request, 'blog/detail.html', {'Post': post})

希望它有所帮助!

答案 1 :(得分:0)

我想编辑Jahongir Rahmonov的答案,因为它不适合我 post_detail函数:

def post_detail(request, post_id):
    post = Post.objects.get(id=post_id)
    if UserSeenPosts.objects.filter(post=post, user=request.user).exists():
        pass
    else:
        post.views += 1
        post.save()
        UserSeenPosts.objects.create(user=request.user, post=post)
    return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)})