utils.py 850 B

12345678910111213141516171819202122232425262728
  1. class MultiQuerySet(object):
  2. def __init__(self, *args, **kwargs):
  3. self.querysets = args
  4. self._count = None
  5. def count(self):
  6. if not self._count:
  7. self._count = sum(len(qs) for qs in self.querysets)
  8. return self._count
  9. def __len__(self):
  10. return self.count()
  11. def __getitem__(self, item):
  12. indices = (offset, stop, step) = item.indices(self.count())
  13. items = []
  14. total_len = stop - offset
  15. for qs in self.querysets:
  16. if len(qs) < offset:
  17. offset -= len(qs)
  18. else:
  19. items += list(qs[offset:stop])
  20. if len(items) >= total_len:
  21. return items
  22. else:
  23. offset = 0
  24. stop = total_len - len(items)
  25. continue