和前端交互全部使用JSON,如何將數據庫查詢結果轉換成JSON格式
返回多條數據
示例
1
2
3
4
5
6
7
|
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" ) |
返回結果
1
2
3
4
5
6
7
8
|
[{ "fields" : { "script_content" : "abc" , "script_type" : "1" }, "model" : "home_application.scripts" , "pk" : "03a0a7cf-567a-11e9-8566-9828a60543bb" }] |
功能實現了,但是我需要返回一個約定好的JSON格式,查詢結果放在 data 中
{"message": 'success', "code": '0', "data": []}
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
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" ) |
調用結果
1
2
3
4
5
6
7
8
9
10
11
12
|
{ "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三個對象,分別代表字段、模型、主鍵,我更想要一個只包含所有字段的字典對象。雖然也可以處理,但還是省點性能,交給前端解析吧。
返回單個對象
代碼:
1
2
3
4
5
6
7
8
9
10
|
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:
1
2
3
4
5
6
|
{ "script_id" : "1534d8f0-59ad-11e9-a310-9828a60543bb" , "script_content" : "3" , "script_name" : "3" , "script_type" : "1" } |
到此這篇關于Django 查詢數據庫返回JSON的實現的文章就介紹到這了,更多相關Django 返回JSON內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_21137441/article/details/113133113