Search code examples
pythondjangodjango-viewsdistinct

Using distinct() function in list. distinct function is not working in list


I am building a Blog App AND I am filtering many queries in one view. I mean, I am filtering two posts which are posted by request.user and By request.user's friends. AND appending all the filtered results in list. BUT when i append all the results then duplicate posts are showing in browser. Then i used distinct() function in list then the error is showing :-

'list' object has no attribute '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)

When i use distinct() and check then the error is keep showing.

I also tried to use distinct() after [:5] in user_post but then it shows.

Cannot create distinct fields once a slice has been taken.

Many Duplicate posts are showing.

Any help would be Much Appreciated.

Thank You in Advance.


Solution

  • if your list is

    >>> 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]
    

    Convert your list as a set and make it list again.

    For your problem you can take a new array and can do it:

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

    It will give you unique posts.