I have a function for getting a dictionary of country names as keys and their cities' names as values. Here is what i did which does not look to be the best way to do it. I am using debugging toolbar that shows 30 sql queries are made for getting this. How should i do it the right way?
#models.py
class City(models.Model):
ci_id = models.AutoField(primary_key=True)
ci_name = models.CharField(max_length=50, blank=True, null=True)
country_co = models.ForeignKey('Country', on_delete=models.CASCADE, null=False)
class Country(models.Model):
co_id = models.AutoField(primary_key=True)
co_name = models.CharField(max_length=50, blank=True, null=True)
#views.py
def get_country_city():
city_dict={}
countries = Country.objects.all()
for country in countries:
c_list =[]
cities = City.objects.filter(country_co__co_id=country.co_id)
for city in cities:
c_list.append(city.ci_name)
city_dict[country.co_name] = c_list
return city_dict
city_dictbeing used for?