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