如何从一个国家获得城市列表,知道该国的城市在Django



我有三个国家、省("州"(和城市的模型。假设我有三个国家——美国、加拿大和英国。此外,假设用户已经选择了奥兰多市(我通过表格获得了这个城市(。现在,我如何在下拉菜单中获取美国的所有城市(假设数据库中来自美国的城市数量有限(。以下是型号:

# country model
class Country(models.Model):
name = models.CharField(max_length=64, unique=True)
def __str__(self):
return "%s" % (self.name)
# province model
class Province(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
def __str__(self):
return "%s" % (self.name)
# city model
class City(models.Model):
province = models.ForeignKey(Province, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
def __str__(self):
return "%s" % (self.name)

我在视图功能中尝试了以下代码:

def search(request):
template = 'path/to/template.html'
#get the name of the city
query_c = request.GET.get('qc') 
# get the country of this city
p_c = Country.objects.filter(province__city__name__iexact=query_c)
print(p_c)
# get a list of cities belong to this country
cities_in_post_city = 
City.objects.filter(province__country__name=p_c)
context={
'all_p_cities': cities_in_post_city,
}
return render(request, template, context )  

我需要一份属于同一个国家的所有城市的名单,只知道一个城市的名字。我不在乎哪个城市属于哪个州。我试着查询这个已知城市的国家。然后发现所有的城市都属于这个国家。我得到的是一个空的查询集。的任何帮助或建议

您可以使用城市模型进行查询:

p_c = Country.objects.filter(province__city__name__iexact=query_c)
cities_in_post_city = City.objects.filter(province__country__in=p_c)
#cities_in_post_city = City.objects.filter(province__country__id__in=p_c)

您可以像一样查询城市模型

cities = City.objects.filter(province__country__name=country_name)

其中country_name是您想要的国家的名称否则,如果你有国家对象,那么你可以像一样查询

cities = City.objects.filter(province__country=country)

通过此,您将获得与该特定国家相关的所有城市

最新更新