重写django的mysql驱动实现原生sql语句查询返回字典类型数据

在使用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类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为您提供一些关于 Django + layui + 原生 SQL 语句实现登录的详细信息。 首先,Django 是一个基于 Python 的 Web 应用程序框架,它可以帮助您快速地构建 Web 应用程序。Layui 是一个流行的前端 UI 框架,它提供了许多易于使用的 UI 组件和样式。原生 SQL 语句是一种直接与数据库进行交互的方式,它可以让您更加灵活地操作数据。 下面是一些实现登录的步骤: 1. 创建 Django 项目并安装必要的包,包括 Django、pymysql 等。 2. 定义数据库模型,可以使用 Django 自带的 ORM,也可以使用原生 SQL 语句。例如,可以创建一个名为 User 的模型,其中包含用户名和密码: ```python class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) ``` 3. 创建登录页面,并使用 Layui 的表单组件和 AJAX 技术提交表单数据。 4. 在后端编写登录验证逻辑,可以使用原生 SQL 语句查询数据库中是否存在对应的用户名和密码。 ```python def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = User.objects.raw('SELECT * FROM user WHERE username=%s AND password=%s', [username, password]) if user: # 登录成功 return JsonResponse({'code': 0, 'msg': '登录成功'}) else: # 登录失败 return JsonResponse({'code': 1, 'msg': '用户名或密码错误'}) ``` 5. 在前端根据后端返回的结果进行相应的处理,例如跳转到首页或者显示错误提示信息。 希望这些信息能对您有所帮助,如有任何问题或需要进一步了解,请随时告诉我。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值