Skip to content

Instantly share code, notes, and snippets.

@robdmc
Created March 23, 2015 20:16
Show Gist options
  • Save robdmc/0b97398a4e6950ce6928 to your computer and use it in GitHub Desktop.
Save robdmc/0b97398a4e6950ce6928 to your computer and use it in GitHub Desktop.
values_list_queryset_chunker
def values_list_queryset_chunker(queryset, chunk_size=10000):
"""
Yields batched querysets from a values_list queryset.
First element of each record must always be pk
"""
queryset = queryset.order_by('pk')
pk = queryset.order_by('pk')[0][0] - 1
batch = queryset.filter(pk__gt=pk)[:chunk_size]
while batch.count() > 0:
chunk_size = min([chunk_size, batch.count()])
pk = batch[chunk_size - 1][0]
yield batch[:chunk_size]
batch = queryset.filter(pk__gt=pk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment