Skip to content

Instantly share code, notes, and snippets.

@ssteuteville
Created April 1, 2016 22:55
Show Gist options
  • Save ssteuteville/1da34d8919642a64f71e53910735b95a to your computer and use it in GitHub Desktop.
Save ssteuteville/1da34d8919642a64f71e53910735b95a to your computer and use it in GitHub Desktop.
batching a query set in django
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