How to filter an item in one queryset from appearing in another queryset in django

Question:

I have a Django view where I am getting the first queryset of ‘top_posts’ by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get "politics_posts" by filtering Posts whose category is "politics". But I want a post appearing in ‘top_posts’, not to appear in ‘politics_posts’.
I have tried using exclude but it seems like it`s not working. Below is my view which is currently not working:

def homepage(request):
    top_posts = Post.objects.all()[:4]
    politics_posts = Post.objects.filter(category='news').exclude(pk__in=top_posts)
    context={"top_posts":top_posts, "politics_posts":politics_posts}
    return render(request, 'posts/homepage.html', context)

Any help will be highly apprecuiated. Thanks.

Asked By: victor

||

Answers:

You will have to change your code to something like this using values_list to get only the pks in a list. Otherwise you are trying to compare a list of Post objects the exclude code

top_posts = Post.objects.all()[:4]
top_post_pks = top_posts.values_list('pk', flat=True)
politics_posts = Post.objects.filter(category='news').exclude(pk__in=top_post_pks)
...

Also maybe you need to do category=politics. In the question you have put category=news

Answered By: Arun T