Django: как посчитать внутренний `sub_comment_set`? - PullRequest
0 голосов
/ 05 августа 2020

как подсчитать внутренний sub_comment_set, вложенный в ManyToManyField. вложенные объекты происходят из comment = models.ManyToManyField(Comments)

, было бы здорово, если бы кто-нибудь мог мне помочь в том, что я пытаюсь решить. Огромное спасибо заранее.

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:

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

1 Ответ

1 голос
/ 05 августа 2020

Использовать prefetch_related + annotate:

Пример:

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

Отредактировано:

Переопределить набор запросов в наборе просмотра

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