Django原生SQL语句查询返回字典

2021/4/15 2:25:17

本文主要是介绍Django原生SQL语句查询返回字典,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在django中执行自定义语句的时候,返回的结果是一个tuple ,并我不是我所期望的dict.
当结果是tuple 时,如果要取得数据,必须知道对应数据在结果集中的序号,用序号的方式去得到值。

如果是python与mysql 方式,这种方式可以得到dict结果

  conn = getConnection(dbparams)
  cursor=conn.cursor(cursorclass = MySQLdb.cursors.DictCursor);
  vreturn=cursor.execute(sql) 

 


但django中,没有cursorclass 这个参数。只能自己去实现

1.根据cursor中的 description 得到各查询的字段名

2.根据得到的结果,把这两个拼凑起来得到结果

fetchone
from django.db import connection
def runquery(sql):    
    cursor = connection.cursor()
    cursor.execute(sql,None)
    col_names = [desc[0] for desc in cursor.description]
    print col_names
    row=cursor.fetchone()
    row = dict(zip(col_names, row))
    print row

现在返回的结果就是 字典类型的了。

 


总结成一个方法:

def dict_fetchall(cursor):
     "将游标返回的结果保存到一个字典对象中"
        desc = cursor.description
        return [dict(zip([col[0] for col in desc], row))
                for row in cursor.fetchall()
        ]

 

直接传入结果的cursor ,就可以得到结果集为dict 的类型。

总结:如果用 django  不是复杂的SQL 查询,尽量用 orm 去完成。如果是比较复杂的SQL语句,涉及到很多表,而且并不完全满足django 的foregion key ,甚至是多个 primary key 对应的话,就自己用 原生的SQL 去完成。可能会更好,但在生成字典的时候,数据量不要太大,没测试过太大会有什么性能问题。但对于小数据量,肯定没问题,基本不用考虑性能。

 

 

自己的一个例子,django  ORM获取数据需要成为字典类型并带入分页中:

 

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute('select count(*) from Message where id>%s', [68900])
    all_count = cursor.fetchone()
    for row in all_count:
        all_count = row

    page_info = PageInfo(request.GET.get('page'), all_count, 10, '/custom.html')  # 拿到PageInfo类中的页码信息

    cursor.execute('select top 75 mtitle,mtype from Message where id>%s', [1])  #取到要显示的具体内容

    def dict_fetchall(cursor):
        "将游标返回的结果保存到一个字典对象中"
        desc = cursor.description
        return [dict(zip([col[0] for col in desc], row))
                for row in cursor.fetchall()[page_info.strat():page_info.end()] #带进来分页内容
        ]
    user_list = dict_fetchall(cursor)

    print(user_list)

 



这篇关于Django原生SQL语句查询返回字典的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程