<s> from collections import defaultdict <EOL> from operator import itemgetter <EOL> from sequere . query import QuerySetTransformer <EOL> from sequere . registry import registry <EOL> import six <EOL> class DatabaseQuerySetTransformer ( QuerySetTransformer ) : <EOL> def __init__ ( self , qs , count ) : <EOL> super ( DatabaseQuerySetTransformer , self ) . __init__ ( qs , count ) <EOL> self . keys = [ ] <EOL> def order_by ( self , key ) : <EOL> self . order_by = key <EOL> self . desc = False <EOL> self . sorting_key = key <EOL> if key . startswith ( '<STR_LIT:->' ) : <EOL> self . desc = True <EOL> self . sorting_key = key [ <NUM_LIT:1> : ] <EOL> self . keys . append ( self . sorting_key ) <EOL> return self <EOL> def aggregate_by ( self , key ) : <EOL> self . aggregate_key = key <EOL> self . keys . append ( self . aggregate_key ) <EOL> return self <EOL> def pivot_by ( self , key ) : <EOL> self . pivot_key = key <EOL> self . keys . append ( self . pivot_key ) <EOL> return self <EOL> def transform ( self , qs ) : <EOL> values = qs [ self . start : self . stop ] . values ( * self . keys ) <EOL> identifier_ids = defaultdict ( list ) <EOL> orders = { } <EOL> for value in values : <EOL> identifier_ids [ value [ self . aggregate_key ] ] . append ( value [ self . pivot_key ] ) <EOL> orders [ value [ self . pivot_key ] ] = value [ self . sorting_key ] <EOL> for identifier , ids in six . iteritems ( identifier_ids ) : <EOL> model = registry . identifiers . get ( identifier ) <EOL> results = model . objects . filter ( pk__in = ids ) <EOL> for result in results : <EOL> created = orders [ result . pk ] <EOL> del orders [ result . pk ] <EOL> orders [ result ] = created <EOL> return sorted ( orders . items ( ) , key = itemgetter ( <NUM_LIT:1> ) , reverse = self . desc ) </s>
