<s> from collections import defaultdict <EOL> def queryset_to_dict ( qs , key = '<STR_LIT>' , singular = True ) : <EOL> """<STR_LIT>""" <EOL> if singular : <EOL> result = { } <EOL> for u in qs : <EOL> result . setdefault ( getattr ( u , key ) , u ) <EOL> else : <EOL> result = defaultdict ( list ) <EOL> for u in qs : <EOL> result [ getattr ( u , key ) ] . append ( u ) <EOL> return result <EOL> def distinct ( l ) : <EOL> """<STR_LIT>""" <EOL> return list ( set ( l ) ) <EOL> from django . db . models . fields . related import SingleRelatedObjectDescriptor <EOL> def attach_foreignkey ( objects , field , related = [ ] , database = '<STR_LIT:default>' ) : <EOL> """<STR_LIT>""" <EOL> is_foreignkey = isinstance ( field , SingleRelatedObjectDescriptor ) <EOL> if not is_foreignkey : <EOL> field = field . field <EOL> accessor = '<STR_LIT>' % field . name <EOL> model = field . rel . to <EOL> lookup = '<STR_LIT>' <EOL> column = field . column <EOL> key = lookup <EOL> else : <EOL> accessor = field . cache_name <EOL> field = field . related . field <EOL> model = field . model <EOL> lookup = field . name <EOL> column = '<STR_LIT>' <EOL> key = field . column <EOL> values = distinct ( getattr ( o , column ) for o in objects if ( related or getattr ( o , accessor , False ) is False ) ) <EOL> if not values : <EOL> return <EOL> qs = model . objects . filter ( ** { '<STR_LIT>' % lookup : values } ) . using ( database ) <EOL> if related : <EOL> qs = qs . select_related ( * related ) <EOL> queryset = queryset_to_dict ( qs , key = key ) <EOL> for o in objects : <EOL> setattr ( o , accessor , queryset . get ( getattr ( o , column ) ) ) <EOL> def attach_foreignkeys ( * object_sets , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> related = kwargs . get ( '<STR_LIT>' , [ ] ) <EOL> database = kwargs . get ( '<STR_LIT>' , '<STR_LIT:default>' ) <EOL> values = set ( ) <EOL> model = None <EOL> for objects , field in object_sets : <EOL> if not model : <EOL> model = field . field . rel . to <EOL> elif model != field . field . rel . to : <EOL> raise ValueError ( '<STR_LIT>' % ( model , field . field . rel . to ) ) <EOL> values . update ( distinct ( getattr ( o , field . field . column ) for o in objects if ( related or getattr ( o , '<STR_LIT>' % field . field . name , False ) is False ) ) ) <EOL> if not values : <EOL> return <EOL> qs = model . objects . filter ( pk__in = values ) . using ( database ) <EOL> if related : <EOL> qs = qs . select_related ( * related ) <EOL> queryset = queryset_to_dict ( qs ) <EOL> for objects , field in object_sets : <EOL> for o in objects : <EOL> setattr ( o , '<STR_LIT>' % field . field . name , queryset . get ( getattr ( o , field . field . column ) ) ) </s>
