【发布时间】:2021-07-30 09:57:37
【问题描述】:
我正在构建一个博客应用程序,并且我在一个视图中过滤了许多查询。我的意思是,我正在过滤由request.user 和By request.user's friends 发布的两个帖子。 AND appending 列表中的所有过滤结果。但是当我 append 所有结果时,重复的帖子会显示在浏览器中。
然后我在列表中使用 distinct() 函数然后显示错误:-
'list' 对象没有属性 'distinct'
models.py
class BlogPost(models.Model):
user = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)
title = models.CharField(max_length=500,default='')
favourites = models.ManyToManyField(User, related_name='favourites ', blank=True)
views.py
def all_blogposts(request):
ALL_POSTS = [].distinct()
#Adding user's post in the list.
user_post = BlogPost.objects.filter(favourites =request.user)[:5]
for post in user_post:
ALL_POSTS.append(post)
#Adding friend's post in the list.
all_posts = BlogPost.objects.all()
requested = request.user.profile.friends.all()
for user_p in requested:
for sets in user_p.user.blogpost_set.all():
ALL_POSTS.append(sets)
context = {'ALL_POSTS':ALL_POSTS}
return render(request, 'all_posts.html', context)
当我使用distinct() 并检查时,错误一直显示。
我也尝试在user_post 中的[:5] 之后使用distinct(),但它显示了。
一旦获取切片,就无法创建不同的字段。
许多重复的帖子正在显示。
非常感谢任何帮助。
提前致谢。
【问题讨论】:
标签: python django django-views distinct