2012-04-10 25 views
2

是否有一种扩展MongoDB游标对象的已知方法,使其与Django的django.core.paginator.Paginator类兼容?将Django的Paginator类与MongoDB游标一起使用

或者,也许,扩展Django的类?

+0

我的临时解决方案:https://gist.github.com/2351079 – Dor 2012-04-10 12:37:49

回答

0

您的临时解决方案(https://gist.github.com/2351079)看起来不错 - 但不是迫使游标读取与list()所有结果,并与[bottom:top]分页,也许尝试光标使用.skip().limit()明确 - 它可能会提高性能。

+0

IIRC游标[foo:bar]与cursor.skip(foo)相同; cursor.limit(bar-foo),即它不创建列表。 – 2012-04-10 23:16:38

+0

只是为了澄清:list(...)函数的使用仅限于'Page'类,所以它只提取当前页面的结果,而不是整个游标。 – Dor 2012-04-11 06:07:51

0

我面临着同样的问题,并实施了我自己的Paginator类。下面的代码:

from django.core.paginator import Paginator, Page 

class MongoPaginator(Paginator): 
    """ 
    Custom subclass of Django's Paginator to work with Mongo cursors. 
    """ 
    def _get_page(self, *args, **kwargs): 
     """ 
     Returns an instance of a single page. Replaced with our custom 
     MongoPage class. 
     """ 
     return MongoPage(*args, **kwargs) 

    def page(self, number): 
     """ 
     Returns a Page object for the given 1-based page number. 
     Important difference to standard Paginator: Creates a clone of the 
     cursor so we can get multiple slices. 
     """ 
     number = self.validate_number(number) 
     bottom = (number - 1) * self.per_page 
     top = bottom + self.per_page 
     if top + self.orphans >= self.count: 
      top = self.count 
     return self._get_page(
      self.object_list.clone()[bottom:top], number, self 
     ) 

class MongoPage(Page): 
    """ 
    Custom Page class for our MongoPaginator. Just makes sure the cursor is 
    directly converted to list so that we can use len(object_list). 
    """ 
    def __init__(self, object_list, number, paginator): 
     self.object_list = list(object_list) 
     self.number = number 
     self.paginator = paginator 

的主要变化是:

  • 每个页面应该得到光标的克隆,因为片每光标只工作一次
  • 每个页面应该也可以直接将其转换为len()工作的列表