how to prefetch comments in django

28 Views Asked by At
class Comment(models.Model):
parent_comment=models.ForeignKey(
    to='self',
    related_name='_comments',
    on_delete=models.DO_NOTHING,
    null=True,
    blank=True,

how to prefetch _comments: child_comment The deeper the depth, the deeper the N+1 query problem

1

There are 1 best solutions below

0
dudu On

I couldn't find anything doing prefetch, so I decided to change the logic eventually. I got the first comment and made a comment that mentions it

If you have any other good content, please let me know!

parent_comment = models.ForeignKey(
    to='self',
    related_name='replies',
    on_delete=models.SET_NULL,
    null=True,
    blank=True,
)
replied_comment = models.ForeignKey(
    to='self',
    related_name='mentions',
    on_delete=models.SET_NULL,
    null=True,
    blank=True,
)