if name == country1: country1 = None country2 = None cont_matches = Location.objects.filter(name__iexact = continent).filter(geographically_in = None) if cont_matches.count() == 0: top_obj = Location(name = continent, submitted_by = mig_user, active = True, locked = True) top_obj.save() else: top_obj = cont_matches[0] for country in (country2, country1): if country: country_matches = top_obj.get_geographic_sub_locations(include_self = False).filter(name__iexact = country) if country_matches.count() == 0: top_obj = Location(name = country, geographically_in = top_obj, submitted_by = mig_user, active = True, locked = True) top_obj.save() else: top_obj = country_matches[0] loc_matches = top_obj.get_geographic_sub_locations(include_self = False).filter(name__iexact = name) if loc_matches.count() == 0: top_obj = Location(name = name, geographically_in = top_obj, submitted_by = mig_user, active = True, locked = True) top_obj.save() else: top_obj = loc_matches[0]