Django 查詢數(shù)據(jù)庫返回JSON的實(shí)現(xiàn)
和前端交互全部使用JSON,如何將數(shù)據(jù)庫查詢結(jié)果轉(zhuǎn)換成JSON格式
返回多條數(shù)據(jù)
示例
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")
返回結(jié)果
[{
"fields": {
"script_content": "abc",
"script_type": "1"
},
"model": "home_application.scripts",
"pk": "03a0a7cf-567a-11e9-8566-9828a60543bb"
}]
功能實(shí)現(xiàn)了,但是我需要返回一個約定好的JSON格式,查詢結(jié)果放在 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)
# 轉(zhuǎn)換為 JSON 字符串并返回
return HttpResponse(json.dumps(result), content_type="application/json")
調(diào)用結(jié)果
{
"message": "success",
"code": "0",
"data": [{
"fields": {
"script_content": "abc",
"script_type": "1"
},
"model": "home_application.scripts",
"pk": "03a0a7cf-567a-11e9-8566-9828a60543bb"
}]
}
有點(diǎn)難受的是,每條數(shù)據(jù)對象包含 fields,model,pk三個對象,分別代表字段、模型、主鍵,我更想要一個只包含所有字段的字典對象。雖然也可以處理,但還是省點(diǎn)性能,交給前端解析吧。
返回單個對象
代碼:
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)
# 轉(zhuǎn)為字典類型
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"
}
到此這篇關(guān)于Django 查詢數(shù)據(jù)庫返回JSON的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Django 返回JSON內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Python中浮點(diǎn)數(shù)精度處理的技巧總結(jié)
雙精度浮點(diǎn)數(shù)(double)是計算機(jī)使用的一種數(shù)據(jù)類型,使用 64 位(8字節(jié)) 來存儲一個浮點(diǎn)數(shù)。下面這篇文章主要給大家總結(jié)介紹了關(guān)于Python中浮點(diǎn)數(shù)精度處理的技巧,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08
Python的基礎(chǔ)語法和輸入輸出函數(shù)你都了解嗎
這篇文章主要為大家詳細(xì)介紹了Python的基礎(chǔ)語法和輸入輸出函數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
Python?使用?pip?安裝?matplotlib?模塊的方法
matplotlib是python中強(qiáng)大的畫圖模塊,這篇文章主要介紹了Python?使用?pip?安裝?matplotlib?模塊(秒解版),本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
Tensorflow實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)擬合線性回歸
這篇文章主要為大家詳細(xì)介紹了Tensorflow實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)擬合線性回歸,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
使用opencv-python如何打開USB或者筆記本前置攝像頭
這篇文章主要介紹了使用opencv-python如何打開USB或者筆記本前置攝像頭的過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

