【问题标题】:Using distinct() function in list. distinct function is not working in list在列表中使用 distinct() 函数。不同的功能在列表中不起作用
【发布时间】:2021-07-30 09:57:37
【问题描述】:

我正在构建一个博客应用程序,并且我在一个视图中过滤了许多查询。我的意思是,我正在过滤由request.userBy 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


    【解决方案1】:

    如果你的列表是

    >>> mylist = [1,1,2,3,3,4,5]
    >>> print(mylist)
    [1, 1, 2, 3, 3, 4, 5]
    >>> mylist = list(set(mylist))
    >>> print(mylist)
    [1, 2, 3, 4, 5]
    

    将您的列表转换为一组并再次列出。

    对于您的问题,您可以采用一个新数组并且可以做到:

    new_array = []
    for post in ALL_POSTS:
        if post not in new_array:
            new_array.append(post)
    

    它会给你独特的帖子。

    【讨论】:

    • 我通过添加 new_list = list(set(ALL_POSTS)) 做到了,但现在什么都没有显示。
    • 一个集合 not 保留元素的顺序,仅对于 small 整数它会保证顺序,因为那时散列函数与身份函数。
    • @Mack 请您通过打印显示您的 ALL_POSTS 中的内容。另外,您是否在上下文之前添加了此代码?
    • 成功了,非常感谢。但是我有一个问题,在大数据中不会这么慢吗?
    • @Mack 显示朋友的帖子是一项复杂的任务。我正在为您描述一个情景,首先您必须显示今天朋友的帖子,然后是第二天......再次,您最喜欢哪个朋友的帖子,这是查询的一个因素。除了那篇文章你已经读过为什么你会在顶部再次看到它?这可能是一个因素。
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    相关资源
    最近更新 更多