(Django) 使用通用 ListView 过滤显示的对象
(Django) filter displayed objects using the generic ListView
我想使用通用的 django ListView 来显示登录用户的所有帖子 url:
#/users/myposts/
url(r'^myposts/', views.MyPostsView.as_view(), name='myposts'),
我的Post模型如下:
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
但是当我 return Post.objects.all()
它 return 所有帖子并显示它们
使用 objects.filter 而不是 objects.get。
我想使用通用的 django ListView 来显示登录用户的所有帖子 url:
#/users/myposts/
url(r'^myposts/', views.MyPostsView.as_view(), name='myposts'),
我的Post模型如下:
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
但是当我 return Post.objects.all()
它 return 所有帖子并显示它们
使用 objects.filter 而不是 objects.get。