def specific_iterator(qs):
 pks_and_types = qs.values_list(u'pk', u'content_type')
 pks_by_type = defaultdict(list)
 for (pk, content_type) in pks_and_types:
  pks_by_type[content_type].append(pk)
 content_types = {pk: ContentType.objects.get_for_id(pk) for (_, pk) in pks_and_types}
 pages_by_type = {}
 for (content_type, pks) in pks_by_type.items():
  model = content_types[content_type].model_class()
  pages = model.objects.filter(pk__in=pks)
  pages_by_type[content_type] = {page.pk: page for page in pages}
 for (pk, content_type) in pks_and_types:
  (yield pages_by_type[content_type][pk])

def specific_iterator ( qs ) : pks_and_types = qs . values_list ( u'pk' , u'content_type' ) pks_by_type = defaultdict ( list ) for ( pk , content_type ) in pks_and_types : pks_by_type [ content_type ] . append ( pk ) content_types = { pk : ContentType . objects . get_for_id ( pk ) for ( _ , pk ) in pks_and_types } pages_by_type = { } for ( content_type , pks ) in pks_by_type . items ( ) : model = content_types [ content_type ] . model_class ( ) pages = model . objects . filter ( pk__in = pks ) pages_by_type [ content_type ] = { page . pk : page for page in pages } for ( pk , content_type ) in pks_and_types : ( yield pages_by_type [ content_type ] [ pk ] )
this efficiently iterates all the specific pages in a queryset .