1
Because you didn’t provide model for city, I wrote it myself:
class State(models.Model):
name = models.CharField(max_length=255)
# id from external source, e.g. 5 from your example
external_id = models.IntegerField()
def fetch_cities_from_network(self):
# Fetching data
resp = requests.get(
'http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/'
'api.php?type=getCities&stateId=%d' % self.external_id
)
# Get dictionary with cities
cities_dict = resp.json()['result']
# Get dictionary values (city names) and save them into the db
for city in cities_dict.values():
City.objects.create(state=self, name=city)
class City(models.Model):
state = models.ForeignKey(State)
name = models.CharField(max_length=255)
And this is how you can use it:
state = State.objects.create(name='Some state', external_id=5)
state.fetch_cities_from_network()
Source:stackexchange.com