刚刚接触python,在学习django使用ajax模式处理数据时,遇到如下问题:
使用django对数据库进行查询,并将查询的QuerySet使用serialize方法序列化为json:
def json_test(request):
data = {}
result = Book.objects.all()
data=serializers.serialize("json", result )
return HttpResponse(data)
得到的data内容为:
[{"model": "techapp.well_designdata", "pk": 1, "fields": {"w_name": "\u5357\u58211-2-36", "w_sumnumber": 3, "w_number": 2}}, {"model": "techapp.well_designdata", "pk": 2, "fields": {"w_name": "\u57d5\u6d772-6", "w_sumnumber": 4, "w_number": 3}}]
问题:1在前端用js处理时如何获取fields内的各个值?
2、在将queryset进行序列化成json时,怎么处理才能不生成model、pk,只生成fields里的内容?就是结果生成的json内容为:
[ {"w_name": "\u5357\u58211-2-36", "w_sumnumber": 3, "w_number": 2}, {"w_name": "\u57d5\u6d772-6", "w_sumnumber": 4, "w_number": 3}]
发在论坛无人解答,最后我的解决方案如下:
对问题1:
前端js:
var ret = eval("("+xhr.responseText+")");
alert(ret[0].fields.w_name);
alert(ret[1].fields.w_name);
对问题2:
后端这样返回json串:
def model2jsonArr(data):
rData = []
for p in data:
p.__dict__.pop("_state") # 除去'model、pk'
rData.append(p.__dict__)
return rData
findwell = well_designdata.objects.all()
data=model2jsonArr(findwell)
return JsonResponse(data, safe=False)
传递到前端的内容:
[{"id": 1, "w_name": "\u5357\u58211-2-36", "w_sumnumber": 3, "w_number": 2}, {"id": 2, "w_name": "\u57d5\u6d772-6", "w_sumnumber": 4, "w_thisnumber": 3]
前端js:
var ret = eval("("+xhr.responseText+")");
alert(ret[0].w_name);
alert(ret[1].w_name);