【问题标题】:how to get list of cities from a country knowing a city in that country in Django如何从一个国家/地区获取城市列表,该国家/地区在 Django 中知道该国家/地区的一个城市
【发布时间】: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


    【解决方案1】:

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

    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)

    【讨论】:

      【解决方案2】:

      您可以像查询城市模型

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2015-06-12
        • 2011-04-28
        • 2011-10-12
        • 2017-06-30
        • 2015-11-18
        • 2012-03-29
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多