i have written a code to get details of city and thier ids.which is in a dictionary form. now i split it in keys and values so that i can store keys to id field and values in city field. i am facing problem when doing it here is my code
models.py
class City(models.Model):
cityid=models.IntegerField(default=0)
city=models.CharField(max_length=50)
views.py
def create(self, request, *args, **kwargs):
r=requests.get('http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=5')
resp = requests.get(
'http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=1'
)
cities_dict = resp.json()['result']
id1=list(cities_dict.keys())
id2=list(cities_dict.values())
for i in id1:
obj1=City.objects.create()
obj1.cityid=i
for j in id2:
obj1.cityid=j
obj1.save()
return HttpResponse (json.dumps(cities_dict))
i know that there is blunder in my views.py please help me thanks in advance
To save id and city you should be doing something like this:
cities_dict = resp.json()['result']
for id in cities_dict:
obj1=City.objects.create(cityid=id, city=cities_dict[id])
obj1.save()
I would rather use dict.items to get the key AND the value in one shot:
cities_dict = resp.json()['result']
for k, v in cities_dict.items():
obj1 = City.objects.create(cityid=k, city=v)
obj1.save()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.