Created
March 23, 2015 20:16
-
-
Save robdmc/0b97398a4e6950ce6928 to your computer and use it in GitHub Desktop.
values_list_queryset_chunker
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 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