How to implement a paginator that doesn't call count(*)

好久不见. 提交于 2021-02-18 05:11:50

问题


I am working on a django website that has a MySQL innodb backend. We have hundreds of thousands of records in several of our tables and this is causing some site stability/performance issues in the admin. Specifically, django likes to make count(*) queries when creating the paginators, and this is causing lots of problems.

With Django 1.3.x, they started to allow for custom pagination classes to be provided. So, I'm interested in finding a way to appropriately speed up or eliminate these queries. So far, I've been looking at these two pages: http://code.google.com/p/django-pagination/source/browse/trunk/pagination/paginator.py https://gist.github.com/1094682 and have not really found them to be what I'm looking for. Any suggestions, help, ect. would be much appreciated.


回答1:


You can define _count variable in your paginator

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

And here is the part of django paginator code to help you understand what this variable do and how page count works

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)



回答2:


You could also check out django-endless-pagination.endless_pagination.paginator.LazyPaginator is not bad, but you might need to add a few tweaks.



来源:https://stackoverflow.com/questions/7707035/how-to-implement-a-paginator-that-doesnt-call-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!