我想使用通用django ListView通过此URL显示已登录用户的所有帖子:
#/users/myposts/
url(r'^myposts/', views.MyPostsView.as_view(), name='myposts'),
我的帖子模型如下:
class Post(models.Model):
person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE)
level = models.ManyToManyField(Level)
date_post = models.DateTimeField()
title = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
is_deleted = models.BooleanField(default=False)
date_delete = models.DateTimeField(null=True)
我的通用ListView是:
class MyPostsView(generic.ListView):
template_name = 'posts_list.html'
userId = None
def get_queryset(self):
return Post.objects.get(person=self.request.user.id)
这样做我收到以下错误消息
get() returned more than one Post -- it returned 2
但是当我返回Post.objects.all()
时
它返回所有帖子并显示它们
答案 0 :(得分:1)
使用objects.filter而不是objects.get。