【问题标题】:How do i increase the integer field when comment is liked喜欢评论时如何增加整数字段
【发布时间】:2020-02-15 11:30:33
【问题描述】:

我有一个评论模型,当评论被点赞时,我想增加一个整数字段。我如何为用户发表的每条评论创建评论。我附上了我尝试过的图片,但仍然没有增加整数字段。

enter image description here

class Comments (models.Model):
    comment_post = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
    commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True)
    comment_likes = models.IntegerField(default=0)
    date = models.DateTimeField(auto_now_add=True)

def comments(request, id):  
    post = get_object_or_404(Image,id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.commented_image = post
            comment.save()
            return redirect('site:comments', id=id)
    else:
        form = CommentForm()
    all_comments = Comments.objects.filter(
        author=request.user.id,
        commented_image=post,
    )
    images = Image.objects.filter(
        imageuploader_profile=request.user.id,
        image_caption=post,
    )
    context = {
        'form': form,
        'all_comments': all_comments,
        'images': images,
    }
    return render(request,'comments.html', context)

【问题讨论】:

  • 请考虑仅通过计数器字段进行跟踪是非常糟糕的做法。由于没有与每个点赞相关的信息,用户很容易通过多次点赞来滥用系统,而您无法阻止它。通常,人们会使用一种新模型来表示喜欢,其中包含用户的外键字段和评论
  • @Hymns,谢谢。我也想到了这一点,我认为这是最好的方法。你能给我一个关于如何完成这个的提示(代码)吗?
  • 我个人之前没有实现过这个,但是你可以在 stackoverflow 和其他网站上找到一些关于如何做到这一点的资源。还有一个 django-likes 包可以为您处理这个问题,并且可以添加到现有项目中

标签: python django


【解决方案1】:

您可能想要构建一个新的端点来处理喜欢的评论

/comment/{id}/like 

包含get_or_404的逻辑 一旦你得到对象集,它就像计数到

comment.comment_likes +=1

你也可以用相反的逻辑来做不同的事情

【讨论】:

  • 厌倦了,但它并没有增加评论。你能设置完整的代码吗?我会附上我尝试过的图片。
  • 检查我附加到我的问题的图像。
猜你喜欢
  • 2013-05-26
  • 2016-03-24
  • 2015-09-10
  • 1970-01-01
  • 2013-11-05
  • 2017-06-07
  • 1970-01-01
  • 2018-12-14
  • 2020-10-07
相关资源
最近更新 更多