和前端交互全部使用JSON,如何将数据库查询结果转换成JSON格式
环境
Win10
Python2.7
Django 1.8.11
返回多条数据
示例
import json
from django.http import HttpResponse
from django.core import serializers
def db_to_json(request):
scripts = Scripts.objects.all()[0:1]
json_data = serializers.serialize('json', scripts)
return HttpResponse(json_data, content_type="application/json")
返回结果
[{
"fields": {
"script_content": "abc",
"script_type": "1"
},
"model": "home_application.scripts",
"pk": "03a0a7cf-567a-11e9-8566-9828a60543bb"
}]
功能实现了,但是我需要返回一个约定好的JSON格式,查询结果放在 data 中
{"message": 'success', "code": '0', "data": []}
代码如下:
import json
from django.http import HttpResponse
from django.core import serializers
def db_to_json2(request):
# 和前端约定的返回格式
result = {"message": 'success', "code": '0', "data": []}
scripts = Scripts.objects.all()[0:1]
# 序列化为 Python 对象
result["data"] = serializers.serialize('python', scripts)
# 转换为 JSON 字符串并返回
return HttpResponse(json.dumps(result), content_type="application/json")
调用结果
{
"message": "success",
"code": "0",
"data": [{
"fields": {
"script_content": "abc",
"script_type": "1"
},
"model": "home_application.scripts",
"pk": "03a0a7cf-567a-11e9-8566-9828a60543bb"
}]
}
有点难受的是,每条数据对象包含 fields,model,pk三个对象,分别代表字段、模型、主键,我更想要一个只包含所有字段的字典对象。虽然也可以处理,但还是省点性能,交给前端解析吧。
返回单个对象
代码:
from django.forms.models import model_to_dict
from django.http import HttpResponse
import json
def obj_json(request):
pk = request.GET.get('script_id')
script = Scripts.objects.get(pk=pk)
# 转为字典类型
script = model_to_dict(script)
return HttpResponse(json.dumps(script), content_type="application/json")
返回JSON:
{
"script_id": "1534d8f0-59ad-11e9-a310-9828a60543bb",
"script_content": "3",
"script_name": "3",
"script_type": "1"
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Django 1.8.11 查询数据库返回JSON格式数据 - Python技术站