2013-03-26 45 views
0

我有一個場景,其中項目是從模型中的項目列表分頁,我想創建一個函數來返回包含此項目的頁面。django在模型中建立一個get_page_url函數返回列表與分頁號碼

例如

class Item(models.Model): 
    subject = models.CharField(max_length=200) 

假設我有表中1000個項目,我總是每頁返回10。我如何在模型中建立一個方法/函數來告訴我該項目會在哪個頁面下降?

請指教?

回答

0

你可以添加一個類方法,它接受一個order_bypaginate_by

import itertools 

def grouper(n, iterable, fillvalue=None): 
    args = [iter(iterable)] * n 
    return itertools.izip_longest(fillvalue=fillvalue, *args) 


class Item(models.Model): 
    # attrs 

    @classmethod 
    def get_pagination_index(cls, self, order_by, paginate_by): 
     if order_by: 
      qs = cls.objects.all().order_by(order_by) 
     else: 
      qs = cls.objects.all() 
     pages = grouper(paginate_by, qs) 
     i = 0 
     for page in pages: 
      i += 1 
      if self in page: 
       return i 

     # return item_index = list(qs).index(self) # get the exact number 
相關問題