我一直收到此错误'发布'对象没有属性' likes_by_set'
Models.py
liked_by = models.ManyToManyField(User, related_name='likedby')
views.py
def like_unlike_article(request, post_id):
a = post.objects.get(id=post_id)
user = request.user
if user is a.liked_by_set.all():
# User has liked it before, means he wants to unlike it
a.liked_by_set.remove(user) # remove him from ``liked_by`` set
a.likes -= 1 # unlike the article
else:
# User wants to like it
a.liked_by_set.add(user) # add him to ``liked_by`` set
a.likes += 1 # like the article
a.save()
任何帮助?
答案 0 :(得分:1)
您应该使用'likes_by'而不是'likes_by_set':
a.liked_by.all()
另请注意,user is a.liked_by_set.all()
将始终返回False
。使用in
子句:
if user in a.liked_by.all():
...
答案 1 :(得分:0)
有多种方法可以解决这个问题。
class Post:
liked_by = models.ManyToManyField(User, related_name='likedby')
这将使以下可能
a = post.objects.get(id=post_id)
a.liked_by.all() # [<User: 1>, <User: 2>]
or
user = request.user
user.liked_by_set.all() # [<Post: 1>, <Post: 2>]
我会创建以下语句
if a.liked_by.get(id=user.id):
...
else:
...
或
if user.liked_by_set.get(id=post_id):
...
else:
...