久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Django 查詢數(shù)據(jù)庫返回JSON的實現(xiàn)

瀏覽:125日期:2024-05-27 14:10:18
目錄返回多條數(shù)據(jù)返回單個對象

和前端交互全部使用JSON,如何將數(shù)據(jù)庫查詢結果轉換成JSON格式

返回多條數(shù)據(jù)

示例

import jsonfrom django.http import HttpResponsefrom django.core import serializersdef 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'}]

功能實現(xiàn)了,但是我需要返回一個約定好的JSON格式,查詢結果放在 data 中

{'message': ’success’, 'code': ’0’, 'data': []}

代碼如下:

import jsonfrom django.http import HttpResponsefrom django.core import serializersdef 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' }]}

有點難受的是,每條數(shù)據(jù)對象包含 fields,model,pk三個對象,分別代表字段、模型、主鍵,我更想要一個只包含所有字段的字典對象。雖然也可以處理,但還是省點性能,交給前端解析吧。

返回單個對象

代碼:

from django.forms.models import model_to_dictfrom django.http import HttpResponseimport jsondef 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 查詢數(shù)據(jù)庫返回JSON的實現(xiàn)的文章就介紹到這了,更多相關Django 返回JSON內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 静宁县| 白山市| 青岛市| 密山市| 大悟县| 汉川市| 民县| 北票市| 定结县| 鄂州市| 双城市| 保亭| 博罗县| 深水埗区| 峨眉山市| 蓬莱市| 莫力| 上杭县| 叙永县| 静乐县| 余江县| 吉首市| 江安县| 扎兰屯市| 邮箱| 甘孜| 丰台区| 顺平县| 定州市| 军事| 迁西县| 东乡族自治县| 都安| 布拖县| 江安县| 南汇区| 台江县| 临高县| 偏关县| 岑溪市| 泽普县|