django为帖子返回作者用户名

时间:2018-05-11 20:00:25

标签: django django-models django-views

我有一个Post模型

class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE,default=None)

在views.py文件中,我尝试根据特定的过滤器返回我正在查看的用户的帖子(到目前为止一切正常),所以:

class UserPosts(generic.ListView):
    model = models.Post
    template_name = "posts/user_post_list.html"
    def get_queryset(self):
            self.y= self.model.objects.filter(user__username__iexact=self.kwargs.get("username"))
            return self.y.filter(message__icontains="jk")

然后我尝试使用用户名(我的模板中的这篇文章的作者),所以我尝试了(这也有效):

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  
        context["post_user"] = self.kwargs.get("username")
        return context

然后我想到了另一种方法(get_context_data方法)。

我认为它应该有用,但它没有......我不知道为什么!所以这里的代码不起作用,并通过我一个错误:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)  
        context["post_user"] = self.y.username
        return context

错误是:

'QuerySet' object has no attribute 'username'

那么为什么我无法通过模型获取用户名?我知道这是错的,但是从模型中提取这些帖子的用户名的正确方法是什么,而不是使用url的slug;我的意思是context["post_user"] = self.kwargs.get("username")

很抱歉,如果这很长,但我尽可能清楚......谢谢

1 个答案:

答案 0 :(得分:1)

self.y的值是一个查询集:

self.y= self.model.objects.filter(user__username__iexact=self.kwargs.get("username"))

执行此操作时:self.y.username您实际上正在尝试从username检索queryset,这会引起明显错误。

如果您倾向于从{strong>帖子 username queryset(特定用户的self.y抓住posts_list,则会输出以下内容用户名:

context["post_user"] = self.y.first().user.username
  

但最好使用你已经知道的context["post_user"] = self.kwargs.get("username")