def queryset_iterator(queryset, chunksize=1000):
    '''''
    Iterate over a Django Queryset ordered by the primary key

    This method loads a maximum of chunksize (default: 1000) rows in it's
    memory at the same time while django normally would load all rows in it's
    memory. Using the iterator() method only causes it to not preload all the
    classes.

    Note that the implementation of the iterator does not support ordered query sets.
    '''
    id = 0
    if queryset.order_by('-id').count() > 0:
        last_pk = queryset.order_by('-id')[0]['id']
        queryset = queryset.order_by('id')
        while id < last_pk:
            for row in queryset.filter(id__gt=id)[:chunksize]:
                id = row['id']
                yield row
            gc.collect()
dataset/ETHPy150Open openstack/stacktach/stacktach/migrations/0003_populate_usage_related_fields_in_rawdataimagemeta_instanceexists_and_instanceusages_from_rawdata.py/queryset_iterator/original