我有一个简单的带有模型的两级注释系统
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循环?