如何从一个国家获取城市列表,了解该国Django的一个城市
我有3个国家、省(“州”)和城市的模型。假设我有三个国家:美国、加拿大和英国。此外,假设用户选择了奥兰多市(我通过表单获得了这个城市)。现在,我如何在下拉菜单中获得美国的所有城市(假设数据库中来自美国的城市数量有限)。以下是模型:如何从一个国家获取城市列表,了解该国Django的一个城市,django,Django,我有3个国家、省(“州”)和城市的模型。假设我有三个国家:美国、加拿大和英国。此外,假设用户选择了奥兰多市(我通过表单获得了这个城市)。现在,我如何在下拉菜单中获得美国的所有城市(假设数据库中来自美国的城市数量有限)。以下是模型: # country model class Country(models.Model): name = models.CharField(max_length=64, unique=True) def __str__(self): r
# 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)
p_c=Country.objects.filter(省、市、名、查询)
城市\在\后\城市=城市.对象.过滤器(省\国家\在=p\ c)
#城市\在\后\城市=城市.对象.过滤器(省\国家\ id \在=p\ c)
您可以使用城市模型进行查询:
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)
p_c=Country.objects.filter(省、市、名、查询)
城市\在\后\城市=城市.对象.过滤器(省\国家\在=p\ c)
#城市位于\u post\u city=city.objects.filter(省\uu国家\uu id\uuu in=p\u c)
您可以查询城市模型,如
cities = City.objects.filter(province__country__name=country_name)
where country\u name是您想要访问的国家的名称
否则,如果您有country对象,那么您可以像
cities = City.objects.filter(province__country=country)
通过此操作,您将获得与特定国家/地区相关的所有城市您可以查询城市模型,如
cities = City.objects.filter(province__country__name=country_name)
where country\u name是您想要访问的国家的名称
否则,如果您有country对象,那么您可以像
cities = City.objects.filter(province__country=country)
通过这一点,您将获得与该特定国家相关的所有城市