首页 > 编程语言 > django 数据库返回queryset实现封装为字典
2020
09-29

django 数据库返回queryset实现封装为字典

默认情况下,Python DB API会返回不带字段的结果,这意味着你得到的是一个列表,而不是一个字典。花费一点性能代价之后,你可以返回一个字典形式的结果,像这样:

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 connection
if __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

这样在前台,就可以通过

{%for i in dic%}
{i.字段}

生成列表了

补充知识:[django] queryset系列化3种方式model_to_dict、serializers

我就废话不多说了,大家还是直接看代码吧!

# 序列化方式1:
from django.forms.models import model_to_dict
import json
data=[]
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 数据库返回queryset实现封装为字典就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自学编程网。

编程技巧