使用外键对模型进行 Django 分页

Django pagination on model with foreign key

Post 和评论模特

class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()

Class 视图 post 详细信息

class PostDetailView(DetailView):
    model = Post
    context_object_name = 'post'
    template_name = 'posts/detail.html'

    def get_queryset(self, *args, **kwargs):
        request = self.request
        pk = self.kwargs.get('pk')
        queryset = Post.objects.filter(pk=pk)
        return queryset

在模板中我做了这样的事情

{% for comment in post.comment_set.all %}
{% comment.content %}
{% endfor %}

在这种方法中,所有评论都显示在 post 详细信息页面中。但是,我想对 post 的评论进行分页,这样我就可以对评论进行分页,而不是显示整个评论列表。

我该怎么做?

django 默认提供分页器。您可以像这样重写 get_context_data 方法来对评论进行分页。

def get_context_data(self, **kwargs):
    context = super(PostDetailView, self).get_context_data(**kwargs)
    comments = context['post'].comment_set.all()
    paginator = Paginator(comments, per_page=50)
    page_number = 1  # get it from query sting or whatever the way you want
    page = paginator.page(page_number)
    context['comments'] = page
    return context

您可以通过像这样循环遍历它们来在模板中呈现 commnet。

{% for comment in comments %}
    {# render comment here. #}
{% endfor %} 

有关渲染分页控件的详细信息,请参阅此处official docs about paginators