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

前端 未结 2 1845
再見小時候
再見小時候 2021-02-13 20:32

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/perfo

2条回答
  •  滥情空心
    2021-02-13 21:20

    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)
    

提交回复
热议问题