Django投票导致重复计算

时间:2019-04-07 10:42:51

标签: python django

我试图简单地完成一项操作:如果用户点击我网站上的“赞”按钮,则对某项投票的计数为+1,但出于某种原因,该计数不为+1,而如果我点击该网址,则为+2帖子:

views.py

def post_up_vote (request, pk):
    post = get_object_or_404(Post, pk=pk)
    try:
        if request.method == 'GET':
            if post.author == request.user:
                messages.error(request, 'You are trying to vote on a Post you created by your own. Thats not possible.')
                return redirect('post_detail', pk=post.pk)
            if Post_Vote.objects.filter(voter=request.user, voted=post).exists():
                messages.error(request, 'You already Voted this Post. Double votes are not allowed.')
                return redirect('post_detail', pk=post.pk)
            else:
                post.up_vote = F('up_vote') + 1
                post.save()
                Post_Vote.objects.create(voter=request.user, voted=post)
                messages.success(request, 'You have successfully Provided an Up-Vote for this Post.')
                return redirect('post_detail', pk=post.pk)
        else:
            messages.error(request, 'Something went wrong, please try again.')
            return redirect('post_detail', pk=post.pk)
    except:
        messages.error(request, 'Something went wrong, please try again.')
        return redirect('post_detail', pk=post.pk)

models.py

class Post(models.Model):
...
up_vote = models.IntegerField(default=0)
down_vote = models.IntegerField(default=0)
...

class Post_Vote(models.Model):

voter = models.ForeignKey(User, on_delete=models.CASCADE)
voted = models.ForeignKey(Post, on_delete=models.CASCADE)
published_date = models.DateField(auto_now_add=True, null=True)

class Meta:
    unique_together = ('voter', 'voted')

def publish(self):
    self.published_date = timezone.now()
    self.save()

urls.py

url(r'^post/(?P<pk>\d+)/up-vote/$', app.post_up_vote, name='post_up_vote'),

template.html

 <a href="{% url 'post_up_vote' pk=post.pk %}"> <i class="btn success fa fa-thumbs-up"></i></a>

如果我在自己的网站上创建了一个新帖子,然后用不同的用户(然后是原始帖子的作者)对该帖子进行投票,则投票数为+2,而不是+1,因此我看不到任何原因。

2 个答案:

答案 0 :(得分:1)

保存模型实例后,分配给模型字段的

F()对象将保留,并将应用于每个save()。

post.up_vote = F('up_vote') + 1
post.save()
post.refresh_from_db()

答案 1 :(得分:0)

您可以尝试post.up_vote += 1