0

I have a scenario where items are paginated from list of items in a model and I want to create a function to return the page which contains this item.

for example

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

Assuming i have 1000 items in the table and i always return 10 per page. How can i build a method/function in the model that would tell me in which page the item would fall?

please advise?

Mo J. Mughrabi
  • 6,747
  • 16
  • 85
  • 143

1 Answers1

0

You could add a classmethod that takes an order_by and paginate_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
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100