Created
March 29, 2021 08:58
-
-
Save Krakenus/3ae9b2a8a1208e6b7280a05e98c9ce08 to your computer and use it in GitHub Desktop.
Django QuerySetBatchIterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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