不断收到此错误 'post' 对象没有属性 'liked_by_set'

Keep getting this error 'post' object has no attribute 'liked_by_set'

我一直收到这个错误 'post' 对象没有属性 'liked_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()

有什么帮助吗?

您应该使用 'liked_by' 而不是 'liked_by_set':

a.liked_by.all()

另请注意,user is a.liked_by_set.all() 将始终 return False。使用 in 子句:

if user in a.liked_by.all():
    ...

您可以通过多种方式解决此问题。

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:
    ...