简体   繁体   中英

How do I create a Django migration to set charset and collation for all existing tables and all future ones?

I'm using Django, Python 3.7 and MySql 5.7. I want to set the default charset and collation for all existing and all future tables to

DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

I have already created some migrations,

(venv) localhost:maps davea$ ls web/maps/migrations/
0001_initial.py  __init__.py  __pycache__

Is there any way I can create such a migration? I'm happy to blow away from database and start from scratch if that's what it takes.

你必须改变数据库的CHARSET,django 与它无关: How to convert a entire MySQL database characterset and collat​​ion to UTF-8?

I came across this problem now where I tried creating a new record where the value of a field_x of type django.db.models.TextField() contains emoticons. It resulted to error:

django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x99\\x82 :...' for column `db_name`.`table_name`.`field_x` at row 1")

I set the charset to utf8mb4 in the proj/settings.py specifically under the DATABASES field:

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

The creation of the record became successful. Also, fetching the created record shows that it correctly contains the saved emoticons.

>>> record = TableName.objects.get(id=93)
>>> record.field_x
'masters trickeds us!!!      MYYYYY PRECIOOOOOUS~!  :) 🙂 :) ^_^🙂^__^'

Some further reference you could check:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM