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

Borhan Tipu
Jan 7, 2022

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)
Model

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__'

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')
List API View

That’s it.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Borhan Tipu
Borhan Tipu

Written by Borhan Tipu

Django Developer & Shopify Expert. Find me: imtipu.me

Responses (1)

Write a response