def get_or_add_location(place_list, mig_user=mig_user): place_list = map(lambda x: x.title(), filter(lambda x: x, place_list)) prev_loc = None prev_tree = Location.objects.all() location_created = False for in_loc_name in reversed(place_list): found_loc = prev_tree.filter(Q(name__exact=in_loc_name), Q(politically_in=None)) found_loc_count = found_loc.count() if found_loc_count > 1: loc = None if prev_loc: immediate_subloc_tree = prev_loc.get_geographic_sub_locations(include_self=False, max_distance=1) immed_found_loc = immediate_subloc_tree.filter(Q(name__exact=in_loc_name), Q(politically_in=None)) if immed_found_loc.count() > 0: # Just taking the first match no matter what for now loc = immed_found_loc[0] if not loc: loc = found_loc[0] # Taking the first match for now elif found_loc_count == 0: loc = Location( name=in_loc_name, geographically_in=prev_loc, active=True, submitted_by=mig_user ) # , log = default_log) loc.save() location_created = True else: loc = found_loc[0] if location_created and not prev_loc.is_root(): raise LocationTooComplicated("Found existing location after having created a non-existent one") else: loc.in_location = prev_loc prev_loc = loc prev_tree = prev_loc.get_geographic_sub_locations(include_self=False) return prev_loc