2012-04-10 1 views
2

장고의 django.core.paginator.Paginator 클래스와 호환되도록 MongoDB 커서 객체를 확장하는 알려진 방법이 있습니까?MongoDB 커서로 Django의 Paginator 클래스 사용

아니면 장고 클래스를 확장할까요?

+0

내 임시 해결 방법 : https://gist.github.com/2351079 – Dor

답변

0

임시 솔루션 (https://gist.github.com/2351079) 좋아 보인다 - 대신 list() 모든 결과를 가져 오기 위해 커서를 강제하고 [bottom:top]와 paginating의, 어쩌면 명시 적으로 커서 .skip().limit()를 사용해보십시오 - 아마도 성능이 향상 될 것입니다.

+0

IIRC 커서 [foo : bar]는 cursor.skip (foo)과 동일합니다. cursor.limit (bar-foo), 즉 목록을 만들지 않습니다. –

+0

그리고 명확히하기 위해 : list (...) 함수의 사용은'Page' 클래스에만 국한되므로 전체 커서가 아닌 현재 페이지의 결과 만 가져옵니다. – Dor

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()이 작동하는 목록