Django:如何迭代包含字典的列表

时间:2018-08-04 12:26:38

标签: django python-2.7 django-templates

我获取Json数据,然后将其转换为python对象。 这是代码:

$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "male"');

while ($row = mysqli_fetch_assoc($resultResource)){ 
  $maleCount = $row['num'];
}

$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "female"');

while ($row = mysqli_fetch_assoc($resultResource)){ 
  $femaleCount = $row['num'];
}

if ($femaleCount > $maleCount){
    //more females in database
}elseif($femaleCount < $maleCount){
    //more males in database
}else{
    //same amount of both;
}

现在,我收到了有效的回复。但无法将这些数据转换为html页面。 我得到的数据如下:

    number = request.POST.get('num')
    url = "http://127.0.0.1:9000/findexclusive"
    querystring = {"num":number}
    response = requests.request("GET", url, params=querystring)
    response = response.json()
    response = json.loads(response)
    return render(request,'home.html',{'details':response})

我该如何迭代。

这些不起作用:

[{u'pk': 1233, u'model': u'details.modelname', u'fields': {a': u'xyz', u'b': u'something', u'c': u'something', u'd': u''}}]

1 个答案:

答案 0 :(得分:0)

当您执行response[0]时,您已经获得了dict项。因此for data in response[0]将为您提供字典的键列表。您可以使用:

for data in response:
     for key,value in data.items:
         print key

还请注意,您可以删除此行response = json.loads(response)。由于response = response.json()已经为您提供了解码的JSON。