<s> from collections import defaultdict <EOL> from django . db . models import Q <EOL> from opencivicdata . models import ( Person , PersonIdentifier , PersonName , PersonContactDetail , <EOL> PersonLink , PersonSource ) <EOL> from . base import BaseImporter <EOL> from . . exceptions import SameNameError <EOL> class PersonImporter ( BaseImporter ) : <EOL> _type = '<STR_LIT>' <EOL> model_class = Person <EOL> related_models = { '<STR_LIT>' : ( PersonIdentifier , '<STR_LIT>' , { } ) , <EOL> '<STR_LIT>' : ( PersonName , '<STR_LIT>' , { } ) , <EOL> '<STR_LIT>' : ( PersonContactDetail , '<STR_LIT>' , { } ) , <EOL> '<STR_LIT>' : ( PersonLink , '<STR_LIT>' , { } ) , <EOL> '<STR_LIT>' : ( PersonSource , '<STR_LIT>' , { } ) , <EOL> } <EOL> def _prepare_imports ( self , dicts ) : <EOL> dicts = list ( super ( PersonImporter , self ) . _prepare_imports ( dicts ) ) <EOL> by_name = defaultdict ( list ) <EOL> for _ , person in dicts : <EOL> by_name [ person [ '<STR_LIT:name>' ] ] . append ( person ) <EOL> for other in person [ '<STR_LIT>' ] : <EOL> by_name [ other [ '<STR_LIT:name>' ] ] . append ( person ) <EOL> for name , people in by_name . items ( ) : <EOL> if len ( people ) > <NUM_LIT:1> : <EOL> for person in people : <EOL> if person [ '<STR_LIT>' ] == '<STR_LIT>' : <EOL> raise SameNameError ( name ) <EOL> return dicts <EOL> def limit_spec ( self , spec ) : <EOL> """<STR_LIT>""" <EOL> if list ( spec . keys ( ) ) == [ '<STR_LIT:name>' ] : <EOL> return ( ( Q ( name = spec [ '<STR_LIT:name>' ] ) | Q ( other_names__name = spec [ '<STR_LIT:name>' ] ) ) & <EOL> Q ( memberships__organization__jurisdiction_id = self . jurisdiction_id ) ) <EOL> spec [ '<STR_LIT>' ] = self . jurisdiction_id <EOL> return spec <EOL> def get_object ( self , person ) : <EOL> all_names = [ person [ '<STR_LIT:name>' ] ] + [ o [ '<STR_LIT:name>' ] for o in person [ '<STR_LIT>' ] ] <EOL> matches = list ( self . model_class . objects . filter ( <EOL> Q ( memberships__organization__jurisdiction_id = self . jurisdiction_id ) , <EOL> ( Q ( name__in = all_names ) | Q ( other_names__name__in = all_names ) ) <EOL> ) . distinct ( '<STR_LIT:id>' ) ) <EOL> matches_length = len ( matches ) <EOL> if matches_length == <NUM_LIT:1> and not matches [ <NUM_LIT:0> ] . birth_date : <EOL> return matches [ <NUM_LIT:0> ] <EOL> elif matches_length == <NUM_LIT:0> : <EOL> raise self . model_class . DoesNotExist ( <EOL> '<STR_LIT>' . format ( all_names , self . jurisdiction_id ) ) <EOL> else : <EOL> if person [ '<STR_LIT>' ] : <EOL> for match in matches : <EOL> if person [ '<STR_LIT>' ] and match . birth_date == person [ '<STR_LIT>' ] : <EOL> return match <EOL> raise self . model_class . DoesNotExist ( <EOL> '<STR_LIT>' . format ( <EOL> all_names , self . jurisdiction_id , person [ '<STR_LIT>' ] ) ) <EOL> raise SameNameError ( person [ '<STR_LIT:name>' ] ) </s>
