djang中的强制严格sql模式

2024-04-27 20:49:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图强制我的django项目始终使用严格的sql_mode。有没有其他方法比在manage.py中放入以下内容更有效?看起来太复杂了。

def set_strict_sql_mode(sender, **kwargs):
    from django.conf import settings
    if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.mysql':
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute('SET session sql_mode=traditional')

from django.core.signals import request_started
request_started.connect(set_strict_sql_mode)

Tags: 项目django方法fromimportdbsqlsettings
4条回答

https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode

设置sql模式

From MySQL 5.7 onwards and on fresh installs of MySQL 5.6, the default value of the sql_mode option contains STRICT_TRANS_TABLES. That option escalates warnings into errors when data are truncated upon insertion, so Django highly recommends activating a strict mode for MySQL to prevent data loss (either STRICT_TRANS_TABLES or STRICT_ALL_TABLES).

If you need to customize the SQL mode, you can set the sql_mode variable like other MySQL options: either in a config file or with the entry 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" in the OPTIONS part of your database configuration in DATABASES.

事实证明,提问是一种很好的方式。在询问之后,我发现定制数据库OPTIONS可以在DATABASES设置中提供,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'sql_mode': 'traditional',
        }
    }
}

希望对任何人都有帮助!

事实证明,问是一个很好的橡皮鸭。在询问之后,我发现定制数据库OPTIONS可以在DATABASES设置中提供,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'sql_mode': 'traditional',
        }
    }
}

希望对任何人都有帮助!

您也可以尝试在数据库[]中添加以下选项

'OPTIONS': {
        'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
    },

它的工作。

相关问题 更多 >