django執(zhí)行原始查詢sql,并返回Dict字典例子
很多時(shí)候執(zhí)行sql語句,數(shù)據(jù)比django的model來的快,但并不想關(guān)心返回的字段,例如你可以執(zhí)行:select * from product這種sql,這里個(gè)方法將會(huì)返回與數(shù)據(jù)庫列名相同的鍵值對 ,格式是這樣子的:
result = [{“id”:1,”name”:”product1”},{“id”:2,”name”:”product2”}]
當(dāng)然你還可以
import json
json.dumps(result )
返回一串json數(shù)據(jù),是不是很完美。。。
# coding:utf-8
from django.db import connection, transaction
'''執(zhí)行django原始sql語句 并返回一個(gè)數(shù)組對象'''
def executeQuery(sql):
cursor = connection.cursor() # 獲得一個(gè)游標(biāo)(cursor)對象
cursor.execute(sql)
rawData = cursor.fetchall()
print rawData
col_names = [desc[0] for desc in cursor.description]
print col_names
result = []
for row in rawData:
objDict = {}
# 把每一行的數(shù)據(jù)遍歷出來放到Dict中
for index, value in enumerate(row):
print index, col_names[index], value
objDict[col_names[index]] = value
result.append(objDict)
return result
補(bǔ)充知識:重寫django的mysql驅(qū)動(dòng)實(shí)現(xiàn)原生sql語句查詢返回字典類型數(shù)據(jù)
在使用django的時(shí)候,有些需求需要特別高的查詢效率,所以需要使用原生的sql語句查詢,但是查詢結(jié)果一般是一個(gè)元組嵌套元組。為了處理方便,需要從數(shù)據(jù)庫查詢后直接返回字典類型的數(shù)據(jù)。
這里使用的方法是繼承django.db.backends.mysql驅(qū)動(dòng)
首先在django項(xiàng)目下創(chuàng)建一個(gè)mysql文件夾,然后在這個(gè)文件夾下創(chuàng)建base.py。
base.py
from django.db.backends.mysql import base
from django.db.backends.mysql import features
from django.utils.functional import cached_property
class DatabaseFeatures(features.DatabaseFeatures):
@cached_property
def is_sql_auto_is_null_enabled(self):
with self.connection.cursor() as cursor:
cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
result = cursor.fetchone()
return result and result['@@SQL_AUTO_IS_NULL'] == 1
class DatabaseWrapper(base.DatabaseWrapper):
features_class = DatabaseFeatures
def create_cursor(self, name=None):
cursor = self.connection.cursor(self.Database.cursors.DictCursor)
return base.CursorWrapper(cursor)
@cached_property
def mysql_server_info(self):
with self.temporary_connection() as cursor:
cursor.execute('SELECT VERSION()')
return cursor.fetchone()['VERSION()']
最后在django項(xiàng)目的settings.py文件里修改數(shù)據(jù)庫配置的數(shù)據(jù)庫引擎
DATABASES = {
'default': {
'ENGINE': 'Test.mysql', # 指定數(shù)據(jù)庫驅(qū)動(dòng)為剛剛創(chuàng)建的mysql文件夾
'NAME': 'test', # 指定的數(shù)據(jù)庫名
'USER': 'root', # 數(shù)據(jù)庫登錄的用戶名
'PASSWORD': '123456', # 登錄數(shù)據(jù)庫的密碼
'HOST': '127.0.0.1',
'PORT': '3306', # 數(shù)據(jù)庫服務(wù)器端口,mysql默認(rèn)為3306
'DATABASE_OPTIONS': {
'connect_timeout': 60,
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
},
}
}
測試
from django.db import connections def f(): search_sql = "SELECT propertyphotoid,propertyid,alykey FROM lansi_architecture_data.propertyphoto limit 0,5" cursor = connections['default'].cursor() try: cursor.execute(search_sql) rows = cursor.fetchall() except Exception as e: print(e) rows = 1 print(rows)
輸出結(jié)果
[{'propertyphotoid': 27, 'propertyid': 0, 'alykey': '123456'}, {'propertyphotoid': 28, 'propertyid': 10837, 'alykey': 'Property/6113/207504A1-AC65-4E3B-BE86-538B3807D364'}, {'propertyphotoid': 29, 'propertyid': 6113, 'alykey': 'Property/6113/357A4EAE-750A-4F59-AF01-271B4225CFBD'}, {'propertyphotoid': 31, 'propertyid': 6113, 'alykey': 'Property/6113/6DF1A2C1-F54C-4462-8363-619806A2F085'}, {'propertyphotoid': 36, 'propertyid': 6113, 'alykey': 'Property/6113/572CB245-ABC0-4FD6-8353-729EBD5E5D46'}]
源碼解析:
django.db.utils.ConnectionHandler的__getitem__方法

獲取連接對象的游標(biāo)是由DatabaseWrapper類的create_cursor返回的。所以只需要重寫create_cursor方法,就可以更改游標(biāo)返回的數(shù)據(jù)類型了。
django.db.backends.mysql.base.DatabaseWrapper類中的create_cursor方法如下:
def create_cursor(self, name=None): cursor = self.connection.cursor() return CursorWrapper(cursor)
到這里,理論上已經(jīng)完成了重寫目標(biāo),但是在測試的時(shí)候出錯(cuò)了,在django.db.backends.mysql.features.DatabaseFeatures里的is_sql_auto_is_null_enabled方法報(bào)出KeyError的錯(cuò)誤。
@cached_property
def is_sql_auto_is_null_enabled(self):
with self.connection.cursor() as cursor:
cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
result = cursor.fetchone()
return result and result[0] == 1
原因是is_sql_auto_is_null_enabled方法使用了重寫后的游標(biāo),cursor.execute('SELECT @@SQL_AUTO_IS_NULL')返回的結(jié)果不是元組,而是一個(gè)字典。所以result[0]會(huì)報(bào)出KeyError的錯(cuò)誤。重寫is_sql_auto_is_null_enabled方法把result[0]改成result['@@SQL_AUTO_IS_NULL']就可以了.
最后還需要把DatabaseWrapper類里的features_class賦值為重寫后的DatabaseFeatures類。
以上這篇django執(zhí)行原始查詢sql,并返回Dict字典例子就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python圖像文字識別詳解(附實(shí)戰(zhàn)代碼)
這篇文章主要給大家介紹了關(guān)于Python圖像文字識別的相關(guān)資料,本文介紹使用python進(jìn)行圖像的文字識別,將圖像中的文字提取出來,可以幫助我們完成很多有趣的事情,需要的朋友可以參考下2024-02-02
Python中處理字符串的相關(guān)的len()方法的使用簡介
這篇文章主要介紹了Python中處理字符串的相關(guān)的len()方法的使用簡介,是Python入門的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
python+Django+pycharm+mysql 搭建首個(gè)web項(xiàng)目詳解
這篇文章主要介紹了python+Django+pycharm+mysql 搭建首個(gè)web項(xiàng)目,結(jié)合實(shí)例形式詳細(xì)分析了python+Django+pycharm+mysql搭建web項(xiàng)目的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
python?import模塊時(shí)有錯(cuò)誤紅線的原因
這篇文章主要介紹了python?import模塊時(shí)有錯(cuò)誤紅線的原因及解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
python常用request庫與lxml庫操作方法整理總結(jié)
一路學(xué)習(xí),一路總結(jié),技術(shù)就是這樣,應(yīng)用之后,在進(jìn)行整理,才可以加深印象。本篇文字為小節(jié)篇,核心總結(jié) requests 庫與 lxml 庫常用的操作2021-08-08
Python ArgumentParse的subparser用法說明
這篇文章主要介紹了Python ArgumentParse的subparser用法說明,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
使用Rasterio讀取柵格數(shù)據(jù)的實(shí)例講解
今天小編就為大家分享一篇使用Rasterio讀取柵格數(shù)據(jù)的實(shí)例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

