1

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?

MaxCore
  • 2,438
  • 4
  • 25
  • 43
  • 1
    But here you do not really *paginate*, since there is no way to obtain the "second page" of *children* for a comment. – Willem Van Onsem Aug 03 '18 at 12:20
  • @WillemVanOnsem, everything is successfully managed by another views+js, just need right initial view – MaxCore Aug 03 '18 at 12:23
  • 1
    Did you try `.prefetch_related('children')`. Maybe you should do it while having the database's logs in a terminal window to see what's going on behind the scenes. I'm afraid that it will get all children of your first page and thus be a bit more inefficient than it needs to be. – Konstantinos Bairaktaris Aug 03 '18 at 12:24
  • @KonstantinosBairaktaris, hmm, I think you are right, definitely have to try it – MaxCore Aug 03 '18 at 12:26

0 Answers0