成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

django執(zhí)行數(shù)據(jù)庫查詢之后實(shí)現(xiàn)返回的結(jié)果集轉(zhuǎn)json

瀏覽:118日期:2024-05-28 14:00:44

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)。

標(biāo)簽: JavaScript
相關(guān)文章: