I'm using itertools.chain
method in Python to chain several Django Querysets
together. By doing so, I'm not touching the database and this is the efficient behaviour I need. However, I'm using a third-party library to paginate these results and this library only accepts list and queryset objects. When calling it with the chain object I get the following error:
Exception Value: 'itertools.chain' object has no attribute '__getitem__'
The line in the library (django-pagemore) that is actually diving me crazy is:
objects = self.objects[page0*self.per_page:1+page*self.per_page]
The problem here is that when using a chain you can't slice it.
I know that I could convert the chain object into a list easily with list()
method, but this would evaluate the ENTIRE queryset and this can contain thousands of items inside.
After some research on how to calculate the size of a Python object
I did some testing and using sys.getsizeof(cPickle.dumps(content))
(where content
is one of the objects inside the chain) gives me a value of 15,915 bytes
, so a chain containing 3,000 of these objects would need 45.53 MB
aprox!