如何从某个国家/地区获取城市列表,从而在Django中了解该国家/地区的城市

时间:2018-10-30 03:15:31

标签: django

我有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 )  

我需要一个列表,列出仅属于城市名称的同一国家的所有城市。我不在乎哪个城市属于哪个州。我试图查询已知城市的国家。然后找到所有城市都属于这个国家。 我得到的是一个空的查询集。任何帮助或建议

2 个答案:

答案 0 :(得分:2)

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

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)

答案 1 :(得分:1)

您可以查询城市模型,例如

cd android
gradlew clean
npm install
react-native run-android

其中country_name是您想要的国家/地区的名称 否则,如果您有国家/地区对象,则可以查询类似

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

这样,您将获得与该特定国家/地区相关的所有城市

相关问题