Django - HttpResponse 2查询结果为JSON格式

时间:2017-03-09 02:23:32

标签: json django

我有2个来自数据库的查询结果,并尝试以json格式返回它。

    gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
    dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
    json_gt_bb = serializers.serialize('json', gt_buffer)
    json_dt_bb = serializers.serialize('json', dt_buffer)
    dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}
    json_bb_buffer = json.dumps(dict_bb_buffer, ensure_ascii=False)

    return HttpResponse(dict_bb_buffer, content_type = "application/json")

在前端,

    $.ajax({
      url: '/results/get_nframebbs',
      data: {
        'exp':_exp,
        'alg':_alg,
        'nframe':data[i]['fields'].nFrame
       },
       dataType: 'json',
       success: function (data) {
          alert(data.length)
       }
    });

但是永远不会调用警报。但是,如果我只是序列化1个查询结果并返回警报,则会通过弹出窗口调用成功。

        gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)

        json_gt_bb = serializers.serialize('json', gt_buffer)



        return HttpResponse(json_gt_bb, content_type = "application/json")

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您的响应是成功函数中的参数,而不是直接的json数据。你可以像这样访问你的数据:

success: function (response) {
      var gt = response.responseJSON.gt;
}

答案 1 :(得分:0)

易。只需将2个查询结果作为字符串返回并在前端解析。

    gt_buffer = ev_ground_truth.objects.filter(alg=_alg, exp=_exp,nFrame=_nframe)
    dt_buffer = ev_detection.objects.filter(alg = _alg, exp=_exp, nFrame=_nframe)
    json_gt_bb = serializers.serialize('json', gt_buffer)
    json_dt_bb = serializers.serialize('json', dt_buffer)
    dict_bb_buffer = {'gt': json_gt_bb, 'dt': json_dt_bb}


    return JsonResponse(dict_bb_buffer, status = 201)

并在前端:

dataType:' json',

     success: function (data) {

                gt = JSON.parse(data.gt.substring(1,data.gt.length-1));
                dt = JSON.parse(data.dt.substring(1,data.dt.length-1));
            }