Created
April 1, 2016 22:55
-
-
Save ssteuteville/1da34d8919642a64f71e53910735b95a to your computer and use it in GitHub Desktop.
batching a query set in django
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
def batch_query_set(query_set, single=False, batch_size=1000): | |
try: | |
last_id = query_set.order_by('-id')[0].id | |
first_id = query_set.order_by('id')[0].id | |
for start in range(first_id, last_id + 1, batch_size): | |
end = min(start + batch_size - 1, last_id) | |
records = query_set.filter(id__range=(start, end)).all() | |
if single: | |
for record in records: | |
yield record | |
else: | |
yield records | |
except IndexError: | |
yield query_set.model.objects.none() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment