在使用django的時候,有些需求需要特別高的查詢效率,所以需要使用原生的sql語句查詢,但是查詢結果一般是一個元組嵌套元組。爲了處理方便,需要從數據庫查詢後直接返回字典類型的數據。
這裏使用的方法是繼承django.db.backends.mysql驅動
首先在django項目下創建一個mysql文件夾,然後在這個文件夾下創建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項目的settings.py文件裏修改數據庫配置的數據庫引擎
DATABASES = {
'default': {
'ENGINE': 'Test.mysql', # 指定數據庫驅動爲剛剛創建的mysql文件夾
'NAME': 'test', # 指定的數據庫名
'USER': 'root', # 數據庫登錄的用戶名
'PASSWORD': '123456', # 登錄數據庫的密碼
'HOST': '127.0.0.1',
'PORT': '3306', # 數據庫服務器端口,mysql默認爲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)
輸出結果
[{'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__方法
獲取連接對象的遊標是由DatabaseWrapper類的create_cursor返回的。所以只需要重寫create_cursor方法,就可以更改遊標返回的數據類型了。
django.db.backends.mysql.base.DatabaseWrapper類中的create_cursor方法如下:
def create_cursor(self, name=None):
cursor = self.connection.cursor()
return CursorWrapper(cursor)
到這裏,理論上已經完成了重寫目標,但是在測試的時候出錯了,在django.db.backends.mysql.features.DatabaseFeatures裏的is_sql_auto_is_null_enabled方法報出KeyError的錯誤。
@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方法使用了重寫後的遊標,cursor.execute('SELECT @@SQL_AUTO_IS_NULL')返回的結果不是元組,而是一個字典。所以result[0]會報出KeyError的錯誤。重寫is_sql_auto_is_null_enabled方法把result[0]改成result['@@SQL_AUTO_IS_NULL']就可以了.
最後還需要把DatabaseWrapper類裏的features_class賦值爲重寫後的DatabaseFeatures類。