zoukankan      html  css  js  c++  java
  • 18.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.根据得到的结果,把这两个拼凑起来得到结果


    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 dictfetchall(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 去完成。可能会更好,但在生成字典的时候,数据量不要太大,没测试过太大会有什么性能问题。但对于小数据量,肯定没问题,基本不用考虑性能。 

  • 相关阅读:
    1600802101
    Android第二次作业
    android 第一次作业
    团队作业—项目答辩
    软件工程—团队作业2.2
    软件工程—团队作业2
    软件工程—团队作业1
    第一篇博客
    Android第四次作业
    作业3
  • 原文地址:https://www.cnblogs.com/413xiaol/p/6528339.html
Copyright © 2011-2022 走看看