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ù)字段顯示對(duì)應(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就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何用 Python 制作一個(gè)迷宮游戲2. vue組件庫的在線主題編輯器的實(shí)現(xiàn)思路3. 網(wǎng)頁中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)4. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟5. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)6. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程7. Django如何使用asyncio協(xié)程和ThreadPoolExecutor多線程8. Python安裝并操作redis實(shí)現(xiàn)流程詳解9. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】10. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解
