[Django]-Force strict sql mode in django

78👍

Actually asking proved to be a good rubber duck. Just after asking, I found the custom database OPTIONS one can supply in the DATABASES settings like this:

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

Hope it helps anyone!

👤jonny

17👍

You can also try with Adding below option in Database []

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

Its working.

1👍

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

Setting sql_mode

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.

0👍

If you need to union the queryset, you can use python chain inster than union.

from itertools import chain

gobj_list = user.groups.all()

robj_list = [obj.roles.all() for obj in gobj_list]

ret_list = chain(*robj_list)

Leave a comment