代码之家  ›  专栏  ›  技术社区  ›  MaxCore

Django:预取和分页相关对象

  •  1
  • MaxCore  · 技术社区  · 8 年前

    class Comment(models.Model):
    
        text = models.TextField()
        parent = models.ForeignKey('self', related_name='children')
    

    现在我这样做:

    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,
        })
    

    每件事都很好,但这看起来是一个糟糕的计划,可能为了性能,它应该是一个查询使用某种方式

    from django.db.models import F, Prefetch .prefetch_related

    有可能吗?或者我可以和for loop呆在一起?

    0 回复  |  直到 8 年前