How to optimize and implement infinite comments through prefetch with django orm?

15 Views Asked by At

I'm implementing the comment function and I can leave a big message in the comments. It was easy to implement the function, but it's causing n+1 queries. Please tell me how to solve this problem

python

Prefetch(
                'comments',
                queryset=PlaceReviewComment.objects.select_related(
                    'user',
                ).prefetch_related(
                    Prefetch(
                        '_comments',
                        queryset=PlaceReviewComment.objects.select_related(
                            'user',
                            'parent_comment',
                        ).prefetch_related(
                            '_comments',
                            '_comments__user',
                        ).filter(
                            removed_at__isnull=True
                        ),
                        to_attr='child_comments'
                    ),
                ).filter(parent_comment=None, removed_at__isnull=True),
                to_attr='_comments'
            ),
        ).filter(
            id=review_id,

If I do this, I'll only get one depth's comment Should I implement a function that does prefetch as much as depth? But I also think to check that there is a _comment and add prefetch, but I don't know how

0

There are 0 best solutions below