我有一个允许用户喜欢该帖子的代码,但我意识到用户可以多次喜欢我不想要的帖子。我该如何限制呢?
我的代码
@login_required
def like_post(request, pk):
if pk:
liked_post = Post.objects.get(id=pk)
count = liked_post.likes
count += 1
liked_post.likes = count
liked_post.save()
return redirect('/community/post/%s' %liked_post.id)
我尝试了什么
添加这样的内容。...但不确定
if post.likes.filter(id=user.id).exists():
post.likes.remove(user)
else:
post.likes.add(user)
答案 0 :(得分:1)
您可以使用unique_together
元类选项。这将引发验证错误,如果您不想报告错误,则可以跳过。
在您的“喜欢”模型中(如果有的话)包括以下内容:
class Meta():
unique_together = ('id', 'user')
或向用户添加“ liked_by
”属性作为many to many field
到应该为您管理uniqueness
内容的用户。该关系只能存在一次。您可以使用Post.liked_by.count()
来获得点赞次数,但是将点赞计数作为自己的属性不会有任何问题。