django 數(shù)據(jù)庫(kù)返回queryset實(shí)現(xiàn)封裝為字典
默認(rèn)情況下,Python DB API會(huì)返回不帶字段的結(jié)果,這意味著你得到的是一個(gè)列表,而不是一個(gè)字典。花費(fèi)一點(diǎn)性能代價(jià)之后,你可以返回一個(gè)字典形式的結(jié)果,像這樣:
def dictfetchall(cursor): 'Returns all rows from a cursor as a dict' desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
demo:
from django.db import connectionif __name__ == ’__main__’: '''db=db_operate() sql=’select DISTINCT t1.HostName,t2.IpAddress,t2.RegName,t2.AppUser,t2.`Desc` from machineinfo as t1,asset_appregioninfo as t2 where t1.IpAddress=t2.IpAddress;’ result=db.mysql_command(settings.conn, sql) dic=dict(result) print dic ''' cur=connection.cursor() cur.execute(’select DISTINCT t1.HostName,t2.IpAddress,t2.RegName,t2.AppUser,t2.`Desc` from machineinfo as t1,asset_appregioninfo as t2 where t1.IpAddress=t2.IpAddress;’) dic=dictfetchall(cur) print dic
這樣在前臺(tái),就可以通過(guò)
{%for i in dic%}{i.字段}
生成列表了
補(bǔ)充知識(shí):[django] queryset系列化3種方式model_to_dict、serializers
我就廢話不多說(shuō)了,大家還是直接看代碼吧!
# 序列化方式1:from django.forms.models import model_to_dictimport jsondata=[]for obj in book_list: data.append(model_to_dict(obj))print(data)return HttpResponse('ok')# 序列化方式2:data=serializers.serialize('json',book_list)return HttpResponse(data)# 序列化方式3:bs=BookSerializers(book_list,many=True)return Response(bs.data)
以上這篇django 數(shù)據(jù)庫(kù)返回queryset實(shí)現(xiàn)封裝為字典就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)2. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息3. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲4. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向5. CSS hack用法案例詳解6. asp中response.write("中文")或者js中文亂碼問(wèn)題7. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法8. PHP設(shè)計(jì)模式中工廠模式深入詳解9. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明10. ASP實(shí)現(xiàn)加法驗(yàn)證碼
