[Answered ]-Paginate data without a queryset in Django?

1👍

Oops, the Paginator works with non-QuerySet objects. From the docs:

Note that you can give Paginator a list/tuple, a Django QuerySet, or any other object with a count() or __len__() method. When determining the number of objects contained in the passed object, Paginator will first try calling count(), then fallback to using len() if the passed object has no count() method. This allows objects such as Django’s QuerySet to use a more efficient count() method when available.

0👍

Is there an object that can help me paginate it, or should I just re-implement my own pagination?

The object does not have to be a QuerySet, it should be an object that accepts obtaining the number of elements with .count() or len(…), and slicing it, so …[lo:hi]. A list for example can also be paginated that way.

Using a list of course often defeats the purpose of paginating: you usually want to prevent loading all elements into memory because that would exhaust the memory, or it would be computationally expensive to do so.

But you thus can make a class that implements the __len__ and __getitem__ methods accordingly, so:

class Paginatable:
    def __init__(self, lo=None, hi=None):
        self.lo = lo
        self.hi = hi

    def __len__(self):
        return 42  # the number of real elements

    def __getitem__(self, slicer):
        if not isinstance(slicer, slice):
            raise TypeError('should only slice')
        else:
            lo = slicer.start if self.lo is None else slicerstart + self.lo
            hi = (
                slicer.stop - slicer.start + lo
                if self.hi is None
                else min(slicer.stop - slicer.start + lo, self.hi)
            )
            return Paginatable(lo=lo, hi=hi)

the Paginatable can then for example process files, do machine learning tasks, etc. to determine the subset of items.

Leave a comment