2017-01-06 38 views
0

我有一个Django视图,我通过模板中的Ajax函数调用。我的模板有'国家'下拉菜单和'区域'(或州)下拉菜单。当用户点击国家时,我想使用Ajax功能获取该国的所有地区(或州),并使用该数据填充“地区”下拉菜单。然而,当我的观点和执行试图返回查询集,我得到这个错误:为什么这个Django错误“太多的值解压缩”?

ValueError: too many values to unpack 

这里是模板标签和Ajax功能:

# demo.html 
<select id="id_country" name="country" onchange="getState(this.value);"> 
    <option value="" selected="selected">Please choose...</option> 
    <option value="US">United States</option> 
    <option value="GB">United Kingdom</option> 
    <option value="CA">Canada</option> 
</select> 

<script> 
function getState(val) { 
    $.ajax({ 
    type: "GET", 
    url: "/demo/get_region", 
    data:'country_id='+val, 
    success: function(data){ 
     $("#id_region").html(data); 
    } 
    }); 
} 
</script> 

这里是视图:

# views.py 
from location.models import CountryRegion 
def get_region(request): 
    country_id = request.GET.get('country_id', None) 
    country_region = CountryRegion.objects.filter(country_cd=country_id) 
    # Error occurs here on the return 
    return country_region 

模型(我知道是不归一化)看起来是这样的:

class CountryRegion(models.Model): 
    country_cd = models.CharField(max_length=2) 
    country_name = models.CharField(max_length=50) 
    region_cd = models.CharField(max_length=3) 
    region_name = models.CharField(max_length=50) 

数据库记录是这样的:

id country_cd country_name region_cd region_name 
59 US   United States NY   New York 

为什么这个错误发生?如果国家代码是'美国',我会 返回50个实例,每个州有一个实例。 Django视图可以返回的数据量有限制吗?

+0

[Django的视图返回JSON的可能的复制没有使用模板](http://stackoverflow.com/questions/9262278/django-view-returning-json-without-using-template) –

+3

你应该返回一个'Response'对象而不是'CountryRegion'对象。请参阅https://docs.djangoproject.com/en/1.10/topics/http/views/ – Gocht

回答

0

,你必须先导入JSON,
进口JSON
然后
返回的HttpResponse( json.dumps(country_region), CONTENT_TYPE = “应用/ JSON” )

相关问题