【问题标题】:'QuerySet' object does not support item assignment'QuerySet' 对象不支持项目分配
【发布时间】:2019-01-24 10:35:04
【问题描述】:
class PostDetailView(DetailView):
    model = Post
    template_name = 'detail.html'

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        instance = Post.objects.get(pk=self.kwargs.get('pk'))
        user = instance.post_user
        context['comments'] = Comment.objects.filter(comment_post=instance.pk)
        context['comments']['profile'] = Profile.objects.get(user=user)
        return context

这是我目前的看法。当我使用该代码时,我收到此错误“QuerySet”对象不支持项目分配。如何正确附加下面的行?

context['comments']['profile'] = Profile.objects.get(user=user)

【问题讨论】:

  • context['profile'] = Profile.objects.get(user=user)??
  • 我正在尝试附加留下评论的用户。通过这样做,我将附加帖子的用户
  • 但是你附加留下评论的用户。 user 始终是 post_user,因为您从不将其定义为其他任何东西。你确定你需要这样做吗?评论是否有指向创建它的用户的链接?你应该展示模型。

标签: python django django-class-based-views


【解决方案1】:

问题在于 context['comments'] 的值不是字典而是 QuerySet 对象。
所以你不能这样做:
context['comments']['profile'] = Profile.objects.get(user=user).

也许您可以将与 Profile 模型的关系添加到 Comment 模型中,例如:

class Comment(models.Model):
    profile = models.ForeignKey(Profile, ...)
    ...

这样您就可以访问发表评论的个人资料的值。

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 2015-03-09
    • 2019-01-03
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2012-01-22
    相关资源
    最近更新 更多