pycharm+Django+MySQL 原生SQL语句查询并显示在前端(转化为dict类型)

简单的查询可以直接用ORM模型来进行查询,但是如果数据库里的表特别多,关系复杂,需要多表连接,那使用原生SQL语句来进行查询更为方便。

1、编写一个将游标返回的结果保存到一个字典对象中的方法。

# 将游标返回的结果保存到一个字典对象中
# 备用函数
# views.py
def dictfetchall(cursor):
    desc = cursor.description
    return [dict(zip([col[0] for col in desc],row))
            for row in cursor.fetchall()]

2、用results得到结果 

#views.py
from django.db import connection

def test(request):
    sql = "select userid,username from user" 
   cursor = connection.cursor()
    cursor.execute(sql)
    results = dictfetchall(cursor) 
    return render(request,"test.html", {"results ": results })

3、templates文件(.html)

{% for temp in results %}
  <tr>
    <td>{{ temp.userid }}</td>
    <td>{{ temp.username }}</td>
  </tr>
{% endfor %}

参考学习网址:https://blog.csdn.net/w55100/article/details/78324566

原文地址:https://www.cnblogs.com/hjy415/p/10858711.html