I have a simple two-level comments system with model
class Comment(models.Model):
text = models.TextField()
parent = models.ForeignKey('self', related_name='children')
In view I need to paginate first and second level comments.
Now I do it like this:
from comments.models import Comment
from django.core.paginator import Paginator
def view(request):
comments = Comment.objects.all()
comments = Paginator(comments, 10).get_page(request.GET.get('page'))
for comment in comments:
children = comment.children.all()
comment.paginated_children = Paginator(children, 10).get_page(1)
return render(request, 'comments.html', {
'comments' : comments,
})
Everything works great, but it looks like a bad plan and probably for performance it should be one query using somehow
from django.db.models import F, Prefetch
and .prefetch_related
Is it possible? Or I can stay with for loop?