django執(zhí)行數(shù)據(jù)庫查詢之后實(shí)現(xiàn)返回的結(jié)果集轉(zhuǎn)json
django執(zhí)行sql語句后得到的返回結(jié)果是一個(gè)結(jié)果集,直接把結(jié)果轉(zhuǎn)json返回給前端會(huì)報(bào)錯(cuò),需要先遍歷轉(zhuǎn)字典在轉(zhuǎn)json,特別注意model_to_dict()只會(huì)將結(jié)果集的第一條數(shù)據(jù)轉(zhuǎn)字典,如果你是根據(jù)指定條件查一條數(shù)據(jù)返回的,直接用model_to_dict()沒問題,如果執(zhí)行的是all()或filter()到多條或全部的數(shù)據(jù),這個(gè)時(shí)候去model_to_dict()這個(gè)集合就不行了,那么先遍歷這個(gè)集合在轉(zhuǎn)字典,然后轉(zhuǎn)json就ok了
dic = {}res = models.tables.objects.all().order_by(’-id’)L = []b = model_to_dict(res)L.append(b)dic[’code’] = ’1’dic[’message’] = ’’dic[’result’] = Lreturn HttpResponse(json.dumps(dic, ensure_ascii=False))
order_by(’-id’):是將結(jié)果集根據(jù)ID倒序排序
補(bǔ)充知識(shí):django執(zhí)行sql根據(jù)字段顯示對應(yīng)的數(shù)據(jù)方式
L = []cursor.execute(sql)desc = cursor.description # 獲取字段的描述,默認(rèn)獲取數(shù)據(jù)庫字段名稱data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] # 列表表達(dá)式把數(shù)據(jù)組裝起來for online_dict in data_dict: # 判斷如果時(shí)間類型要轉(zhuǎn)出字符串,后期碰到什么類型不能轉(zhuǎn)的在加 for key in online_dict: if type(online_dict[key]) in (datetime, pymysql.TIMESTAMP, pymysql.DATE, pymysql.TIME, YEAR): online_dict[key] = online_dict[key].strftime('%Y-%m-%d %H:%M:%S') else: pass L.append(online_dict)conn.commit()cursor.close()conn.close()dic[’code’] = ’2’dic[’message’] = ’’dic[’result’] = Lreturn HttpResponse(json.dumps(dic, ensure_ascii=False))
以上這篇django執(zhí)行數(shù)據(jù)庫查詢之后實(shí)現(xiàn)返回的結(jié)果集轉(zhuǎn)json就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python用pyecharts實(shí)現(xiàn)地圖數(shù)據(jù)可視化2. python+requests+pytest接口自動(dòng)化的實(shí)現(xiàn)示例3. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法4. 詳解Python 3.10 中的新功能和變化5. npm下載慢或下載失敗問題解決的三種方法6. ASP編碼必備的8條原則7. Python中re模塊的常用方法總結(jié)8. python基于opencv批量生成驗(yàn)證碼的示例9. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式10. 如何用python開發(fā)Zeroc Ice應(yīng)用
