Posts which are not liked by user

I am building a Blog App and I am trying to show posts which are not liked by request.user,

  • I have tried using Exists method as Mentioned :-
from django.db.models import Exists

checkIt = BlogPost.objects.annotate(is_liked=Exists(
                Like.objects.filter(user=request.user)))

But it is showing all the posts.

models.py

class BlogPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE)

views.py

def unliked_posts(request):

    posts = BlogPost.objects.filter(like__user=request.user).exclude(like__user=request.user)

    context = {'posts':posts}
    return render(request, 'unliked_posts.html', context)

I have tried many time but it didn’t worked for me.

I will really appreciate your Help. Thank You

Answer

You can work with a simple exclude(…) [Django-doc]:

posts = BlogPost.objects.exclude(like__user=request.user)