【发布时间】:2020-05-14 06:07:43
【问题描述】:
我目前正在学习 Django 并为此构建一个类似 twitter 的应用程序。
我在我的个人资料模型中使用了 ManyToManyField 来反映关注者:
models.py
>class Profile(models.Model):
"""
Extension of User model to save additional information
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
followers = models.ManyToManyField('self', related_name='Followers', blank=True, symmetrical=False)
follower_count = models.IntegerField(default=0)
following_count = models.IntegerField(default=0)
现在我正在尝试检查用户是否已经在关注另一个用户(打开个人资料以便我可以在那里显示正确的关注/取消关注按钮时)
views.py
>def profile(request, username):
try:
user = User.objects.get(username=username)
user_profile = Profile.objects.get(user_id=user.id)
except ObjectDoesNotExist:
raise Http404("User does not exist")
is_following = True if user.id in Profile.followers.all() else False
return render(request, 'songapp/profile.html', {'user_profile': user_profile,
'user' : user,
'is_following': is_following})
问题出在
Profile.followers.all()
当我得到以下 AttributeError 时:
'ManyToManyDescriptor' object has no attribute 'all'
我已经使用了搜索功能并阅读了长达 8 岁的结果,但我没有找到或理解相应的答案。
非常感谢任何帮助
【问题讨论】:
-
您正在尝试通过模型而不是模型实例获取 M2M 记录。这应该是更具体的东西。试试这个,例如
Profile.objects.filter(id=1).followers.all() -
这样我得到了
'QuerySet' object has no attribute 'followers'- 但这是一个变化,所以我们可能走在正确的轨道上。 -
哦,对不起,忘记了我提到的“更具体”的细节:
Profile.objects.filter(id=1).last().followers.all() -
您是否有可能忘记运行迁移?奇怪的是,当您在 M2M 字段上设置了
symmetrical=False时它不起作用。只是想知道如果您将其称为Profile._meta.get_fields()会是什么输出 -
哈,很高兴它有帮助!如果有用,您可以对我的评论进行投票。