Wagtail项目中的分页:在模型中分离分页逻辑的更好方法?

2024-05-16 07:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一个来自Wagtail项目中的HomePage模型的片段,它充当了我的博客索引页。由于get_context()在添加Django的分页逻辑时变得有点冗长,所以我决定尝试将其放入自己的方法中,并让get_context()从中获取Page对象的分页集合。下面是我的代码最初的样子:

class HomePage(RoutablePageMixin, Page):
    description = models.CharField(max_length=255, blank=True, null=True)

    content_panels = Page.content_panels + [
        FieldPanel('description', classname='full')
    ]

    def get_context(self, request, *args, **kwargs):
        context = super(HomePage, self).get_context(request, *args, **kwargs)
        context['posts'], context['page_range'] = self.pagination(self.get_posts())
        # End attempt
        context['home_page'] = self
        context['search_type'] = getattr(self, 'search_type', '')
        context['search_term'] = getattr(self, 'search_term', '')
        return context


    def get_posts(self):
        return BlogPage.objects.descendant_of(self).live().order_by('-date')


    def pagination(self, posts):
        paginator = Paginator(posts, 5)
        try:
            page = request.GET.get('page', '1')
        except:
            page = 1
        try:
            posts = paginator.page(page)
        except PageNotAnInteger:
            posts = paginator.page(1)
        except EmptyPage:
            posts = paginator.page(paginator.num_pages)
        # Get a page_range
        index = posts.number - 1
        max_index = len(paginator.page_range)
        start_index = index - 5 if index >= 5 else 0
        end_index = index + 5 if index <= max_index - 5 else max_index
        page_range = paginator.page_range[start_index:end_index]
        print('\n', posts, '\n')
        return posts, page_range

我没有立即发现问题,但当然注意到无论URL中的page参数是什么,页面1都在被服务。我快速而肮脏的解决方案是在pagination()中添加request作为参数,然后在get_context()中向上传递{}。这解决了问题,但我忍不住认为这个解决方案有问题,或者它不是最佳实践。有谁能告诉我一个更好的方法来解决这个问题和/或是在不修改变量的情况下从一个函数传递到另一个函数是否是个坏主意?还是真的很好?在

下面是我的代码现在的样子,一切似乎都正常工作:

^{pr2}$

提前感谢大家!在


Tags: selfsearchgetindexrequestdefcontextpage