satyajit
satyajit

Reputation: 694

Django: how to count inner `sub_comment_set`?

how to count the inner sub_comment_set that nested in ManyToManyField.
the nested objects comes from comment = models.ManyToManyField(Comments)

it would be great if anybody could help me what i am trying to solve. thank you so much in advance.

models.py:

class Comments(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

class SubComments(models.Model):
    comment = models.ManyToManyField(Comments)


serializers.py:
class CommentsSerializer(serializers.ModelSerializer):
    subcomments_set = SubCommentsSerializer(many=True)
    class Meta:
        model = Comments
        fields = [
            "id", "post_title", "name", "cover", "email", "subject",
            "subcomments_set",
            
        ]

views.py

class CommentListAPIView(generics.ListAPIView):
    model = Comments
    queryset = Comments.objects.filter(status=1)
    serializer_class = CommentsSerializer

class SubCommentListAPIView(generics.ListAPIView):
    model = SubComments
    queryset = SubComments.objects.filter(status=1)
    serializer_class = SubCommentsSerializer

API data:

[
  {
        "id": 2,
        "post_title": "chilika_photography_02",
        "name": "kimberly",
        "cover": "/media/author_cover/batman.jpg",
        "email": "[email protected]",
        "subject": "kimberly messages...",
        "subcomments_set": [
            {
                "id": 4,
                "name": "zatty",
                "email": "[email protected]",
                "subject": "zatty messages02....",
                "datetime": "08/05/2020"
            },
            {
                "id": 6,
                "name": "zatty",
                "email": "[email protected]",
                "subject": "zatty messages04....",
                "datetime": "08/05/2020"
            }
        ]
    },
]

Upvotes: 0

Views: 64

Answers (1)

vpdiongzon
vpdiongzon

Reputation: 679

Use prefetch_related + annotate:

example:

Comments.objects.prefetch_related('sub_comments_set').annotate(count=Count('sub_comments_set'))

Edited:

Override queryset on viewset

class CommentListAPIView(generics.ListAPIView):
    model = Comments
    queryset = Comments.objects.filter(status=1)
    serializer_class = CommentsSerializer

    def get_queryset(self):
         return Comments.objects.prefetch_related('sub_comments_set').annotate(count=Count('sub_comments_set'))

Upvotes: 1

Related Questions