我要改名叫嘟嘟
我要改名叫嘟嘟

Reputation: 169

Django MySQL charset setting is not working, utf8mb4 changed to utf8

My setting file is looks like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        # ...
        'OPTIONS': {
            'charset': 'utf8mb4',
        }
    },
}

After some migrates(like python manage.py migrate zero, python manage.py reset_db..), the MySql encoding changed from utf8mb4 to utf8.

enter image description here

docker volume ls
docker volume rm -f xx    # this not work, say "xx volume is in use"

# use this one cleard the volume.
docker-compose -f xx.yml down --volumes

I use above command to recreate docker volumes fix it, But I wanna know why, so here is the question.

My docker-compose file looks like:

# ...
services:
  # ...
  db:
    image: mysql:5.7.18
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
# ...

Upvotes: 0

Views: 769

Answers (1)

我要改名叫嘟嘟
我要改名叫嘟嘟

Reputation: 169

While I asking this question, I try to look Django source code to find why, It's help me think more about my question, I try to reproduce this question,there are steps:

  1. First the database was created by docker-compose, MySql's charset is utf8mb4.
  2. Then execute "python manage.py migrate" to create tables.
  3. I wanna merge the migrations to one, so I use these cmd to do it.
python manage.py migrage xx zero
rm xx/migrations/00*.py
python manage.py reset_db
python manage.py makemigrations
python manage.py migrate
  1. I checked the cmd, db changing is from python manage.py reset_db.

So I goto find reset_db did what from django_extensions.

Here is the code:

# file: management.commands.reset_db.py
# ...
connection = Database.connect(**kwargs)
drop_query = 'DROP DATABASE IF EXISTS `%s`' % database_name
utf8_support = '' if options['no_utf8_support'] else 'CHARACTER SET utf8'
create_query = 'CREATE DATABASE `%s` %s' % (database_name, utf8_support)
logging.info('Executing... "%s"', drop_query)
connection.query(drop_query)
logging.info('Executing... "%s"', create_query)
connection.query(create_query.strip())
# ...

reset_db first drop database, then create database.

I give the cmd one arg

python manage.py reset_db --no-utf8

then the database's encoding changed to utf8mb4.

Upvotes: 1

Related Questions