15

我正在开发一个具有 MySQL innodb 后端的 django 网站。我们的几个表中有数十万条记录,这导致了管理员中的一些站点稳定性/性能问题。具体来说,django 喜欢在创建分页器时进行 count(*) 查询,这会导致很多问题。

在 Django 1.3.x 中,他们开始允许提供自定义分页类。因此,我有兴趣找到一种适当加快或消除这些查询的方法。到目前为止,我一直在看这两个页面:http ://code.google.com/p/django-pagination/source/browse/trunk/pagination/paginator.py https://gist.github.com/ 1094682 并没有真正找到它们是我正在寻找的东西。任何建议,帮助等。将不胜感激。

4

3 回答 3

12

您可以在分页器中定义 _count 变量

  paginator = Paginator(QuerySet, 300)
  paginator._count = 9000 # or use some query here

这是 django 分页器代码的一部分,可帮助您了解此变量的作用以及页数的工作原理

def _get_count(self):
    "Returns the total number of objects, across all pages."
    if self._count is None:
        try:
            self._count = self.object_list.count()
        except (AttributeError, TypeError):
            # AttributeError if object_list has no count() method.
            # TypeError if object_list.count() requires arguments
            # (i.e. is of type list).
            self._count = len(self.object_list)
    return self._count
count = property(_get_count)
于 2011-11-02T21:25:53.347 回答
1

您可以自己通过计数

paginator = Paginator(models ,25 )
paginator.count=100000

或者如果你想要确切的计数,你可以使用

count=int(model.objects.latest('id').id)
paginator = Paginator(models ,25 )
paginator.count=count
于 2021-09-11T21:25:02.987 回答
-1

您还可以查看django-endless-paginationendless_pagination.paginator.LazyPaginator还不错,但您可能需要添加一些调整。

于 2012-01-22T07:45:59.167 回答