【发布时间】:2018-10-30 03:15:30
【问题描述】:
我有国家、省(“州”)和城市的 3 个模型。假设我有 3 个国家美国、加拿大和英国。此外,假设用户选择了奥兰多市(我通过表格获得了这个城市)。现在,如何在下拉菜单中获取美国的所有城市(假设数据库中来自美国的城市数量有限)。以下是模型:
# 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 )
我需要一份属于同一个国家的所有城市的列表,只知道一个城市名称。我不在乎哪个城市属于哪个州。我试图查询已知城市的国家。然后找到所有城市属于这个国家。 我得到的是一个空的查询集。任何帮助或建议
【问题讨论】:
标签: django