Django 1.8.11 查询数据库返回JSON格式数据
和前端交互全部使用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',