Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

show all likes count in each post django REST API

models.py

class Post(models.Model):
   title = models.CharField(max_length=150)

class PostLike(models.Model):
    like = models.CharField(max_length=20)
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

Serializer.py

class PostSerializer(serializers.ModelSerializer):
    likes = serializers.SerializerMethodField("like_count")
    class Meta:
        model = Post
        fields  = ("__all__")

    def like_count(self,obj):
        total_like = self.context.get("like_count")
        return total_like

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@api_view(["POST"])
def allpost(request):
    id = request.data    
    post_list = Post.objects.all()
    like_count = PostLike.objects.filter(post_id = id ).count()
    post_serializer = PostSerializer(post_list,many=True,context={"like_count":like_count})
    return Response(request,post_serializer.data)

urls.py

urlpatterns = [
 path('post/',views.allpost,name="post"),
]

output:

[
{
  "id": 1,
  "likes": 1,
  "title": "post 1",
},
{
  "id": 2,
  "likes": 1,
  "title": "post 2",
},
{
  "id": 3,
  "likes": 1,
  "title": "post 3",
},
]

db

id like post_id user_id
1   1     1      1
2   1     2      1
3   1     1      2

actually in my db likes are:
post 1 have 2 likes
post 2 have 1 like
post 3 don’t have any like

i want to show this like this .
but it’s showing the first post likes for every post .
how can i fix this .?
i know the problem in the like_count in view .
but i don’t know what to put there instead of id .

sorry for my poor English
Thanks in advance

>Solution :

Use relationships, it helps a lot. Define a function in Post model, so serializer can get it easily.

models.py:

class Post(models.Model):
   title = models.CharField(max_length=150)

   def likes_count(self):
       return self.likes.all().count()

class PostLike(models.Model):
    like = models.CharField(max_length=20)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_likes')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')

serializers.py:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields  = ["id", "title", "likes_count"]

    # That part you can delete
    # def like_count(self,obj):
    #     total_like = self.context.get("like_count")
    #     return total_like

views.py:

@api_view(["POST"])
def allpost(request):
    post_list = Post.objects.all()
    post_serializer = PostSerializer(post_list, many=True)
    return Response(request, post_serializer.data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading