Skip to content

Instantly share code, notes, and snippets.

@Krakenus
Created March 29, 2021 08:58
Show Gist options
  • Save Krakenus/3ae9b2a8a1208e6b7280a05e98c9ce08 to your computer and use it in GitHub Desktop.
Save Krakenus/3ae9b2a8a1208e6b7280a05e98c9ce08 to your computer and use it in GitHub Desktop.
Django QuerySetBatchIterator
class QuerysetBatchIterator:
def __init__(self, qs, batch_size=1000):
self.qs = qs
self.batch_size = batch_size
self._total = None
def __iter__(self):
for start in range(0, self.total, self.batch_size):
end = min(start + self.batch_size, self.total)
yield self.qs[start:end]
@property
def total(self):
if self._total is None:
self._total = self.qs.count()
return self._total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment