DEV Community

Cover image for Django: How to show a user liked a post or not in List View without Duplicate Queries.
Borhan Tipu
Borhan Tipu

Posted on • Updated on

Django: How to show a user liked a post or not in List View without Duplicate Queries.

Create a model if you don’t have:

class PostLike(models.Model):
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='post_likes')
    post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, related_name='likes')

    created = models.DateTimeField(auto_now_add=True)
Enter fullscreen mode Exit fullscreen mode

Code for Rest Framework

Create a Model Serializer for Post Model. is_liked will be Boolean field and read only.

class PostSerializer(serializers.ModelSerializer):
    is_liked = serializers.BooleanField(read_only=True)
    class Meta:
      model = Post
      fields = '__all__'
Enter fullscreen mode Exit fullscreen mode

Create a Rest ListAPIView PostListAPIView. Use authentication class to get the request.user.

from django.db.models import Prefetch, Exists, OuterRef

class PostListAPIView(ListAPIView):
    serializer_class = PostSerializer
    queryset = Post.objects.none()

    def get_queryset(self):
        return Post.objects \
            .annotate(is_liked=Exists(PostLike.objects.filter(
            user=self.request.user, post_id=OuterRef('pk')))) \
            .order_by('title')
Enter fullscreen mode Exit fullscreen mode

That’s it.

You can contact me to talk about your projects, build new applications, etc.

Hire Me: shorturl.at/jlAB5
Linked In: https://www.linkedin.com/in/borhantipu

Top comments (0)