0

i want to count comments for every single Post

in models.py:

class Post(models.Model):
    body = models.TextField(max_length=10000)
    date = models.DateTimeField(auto_now_add=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by')

    class Meta:
        ordering = ['-date']

class Comment(models.Model):
    body = models.TextField(max_length=1000)
    date = models.DateTimeField(auto_now_add=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    class Meta:
        ordering = ['-date']

in serializers.py:

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    #comments = CommentSerializer()
    user = UserSerializers()
    total_likes = serializers.SerializerMethodField()
    liked_by = SimpleUserSerializer(many=True, read_only=True)
    total_comments = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('body','date','user', 'total_likes', 'liked_by','total_comments')

    def get_total_likes(self, instance):
        return instance.liked_by.count()

    def get_total_comments(self, instance):
        return instance.comments.count()

when i run this code, it shows, AttributeError: 'Post' object has no attribute 'comments'.

how do i count comments of a post?

Asif Biswas
  • 161
  • 2
  • 9

1 Answers1

1

Since you haven't configured the related_name, Django uses the default related_name and hence you should access the reveres FK using comment_set instead of comments

Thus, the get_total_comments(...) method should look like

def get_total_comments(self, instance):
    return instance.comment_set.count()

Reference

JPG
  • 82,442
  • 19
  • 127
  • 206
  • sir, it's not working. showing, **django.db.utils.ProgrammingError: relation "fb_comment" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fb_comment" WHERE "fb_com...** my app name is **fb** – Asif Biswas Dec 15 '20 at 04:00
  • sir, it works. i rename the model name. but did not makemigrations – Asif Biswas Dec 15 '20 at 04:48