Django 1.8.11 查询数据库返回JSON格式数据

Django 1.8.11 查询数据库返回JSON格式数据

和前端交互全部使用JSON,如何将数据库查询结果转换成JSON格式

环境

Win10
Python2.7
Django 1.8.11

使用 Django 的序列化支持

示例

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": []}

代码如下:

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三个对象,分别代表字段、模型、主键,我更想要一个只包含所有字段的字典对象。虽然也可以处理,但还是省点性能,交给前端解析吧。

猜你喜欢

转载自www.cnblogs.com/eoalfj/p/10653334.html