[在ListView中将get_context_Data用于paginate_by时,页面显示所有行

问题描述 投票:1回答:3

在Django中这个简单的通用视图中的分页正在工作,但是每个页面显示所有行,而不显示该页面的行。如何只选择给定页面所需的记录?

class ArticleList(ListView):
    """Get all articles"""
    model = Article
    template_name = "blog/articles.html"
    paginate_by = 4

    def get_context_data(self, **kwargs):
        context = super(ArticleList, self).get_context_data(**kwargs)
        context['articles'] = Article.objects.select_related().all()

        return context
python django django-generic-views
3个回答
2
投票

因为您已覆盖articles中的get_context_data对象以返回所有内容。默认实现在那里进行分页,但是您已经用非分页查询集替换了它。

相反,定义get_queryset并在其中添加select_related


1
投票

这是我刚开始解决它的方式:

class ArticleList(ListView):
"""Get all articles"""
model = Article
template_name = "blog/articles.html"
paginate_by = 1

def get_context_data(self, **kwargs):
    context = super(ArticleList, self).get_context_data(**kwargs)
    p = Paginator(Article.objects.select_related().all(), self.paginate_by)
    context['articles'] = p.page(context['page_obj'].number)

    return context

但是,在所有人的帮助下,最佳方法是:

class ArticleList(ListView):
"""Get all articles"""
model = Article
template_name = "blog/articles.html"
paginate_by = 1
context_object_name = "articles"

def get_queryset(self):
    return Article.objects.all().order_by('-date')

谢谢。


0
投票
class ArticleList(ListView):
    """Get all articles"""
    model = Article
    template_name = "blog/articles.html"
    paginate_by = 4

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_posts = Article.objects.select_related().all()
        p = Paginator(user_posts, self.paginate_by)
        page = self.request.GET.get('page', 1)

        try:
            context['posts'] = p.page(page)
        except EmptyPage:
            context['posts'] = p.page(p.num_pages)
        return context

为了避免EmptyPage错误,您可以使用上面的代码

© www.soinside.com 2019 - 2024. All rights reserved.