-1

I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are:

DATABASES = {   
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',
        },
    }
}

'charset': 'utf8mb4',

This parameter seems don't work properly and tables in DB utf8. Although i want to manually set and tables Collation to utf8mb4_general_ci

Will be appreciate for any clues.

Denis
  • 659
  • 1
  • 9
  • 21

2 Answers2

3
'default': {
    'ENGINE': 'django.db.backends.mysql', 
    'NAME': '',
    'USER': '',
    'PASSWORD': '',
    'HOST': 'localhost',
    'PORT': '3306',
    'OPTIONS': {
        'init_command': 'ALTER DATABASE <YOUR_DB_NAME> CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci',
    },
}

Thanks to https://stackoverflow.com/a/6115705/2891421

Denis
  • 659
  • 1
  • 9
  • 21
  • 5
    Note that init_command runs on every new connection - is `ALTER DATABASE CHARACTER SET` cheap to run if no changes are required? It seems unwise, a one-off migrations using RunSQL seems like a much safer alternative https://docs.djangoproject.com/en/dev/ref/migration-operations/#runsql – John Carter Nov 04 '18 at 20:37
0
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': get_env_val('MYSQL_DB_NAME'),
        'USER': get_env_val('MYSQL_DB_USER'),
        'PASSWORD': get_env_val('MYSQL_DB_PASSWORD'),
        'HOST': get_env_val('MYSQL_DB_HOST'),
        'PORT': get_env_val('MYSQL_DB_PORT'),
        'OPTIONS': {
            'charset': 'utf8mb4',
        }
        ,
    }
}
PLABON DATTA
  • 167
  • 1
  • 4