Search code examples
mysqldjangoutf8mb4

Django "Illegal mix of collations" for MySQL utf8mb4 table


I have reviewed other questions related to this topic, such as django python collation error

However, the solutions say to encode the table using a utf8 charset. That is not a viable solution for our modern Django app running on a utf8mb4-encoded database.

In my case, I need to enforce a charset or collation in the Django generated query, or in the DB itself, when utf-8 characters are being passed in (from a call to model.objects.get_or_create(), I believe with an emoji character being passed in one of the kwargs fields.)

I'm getting this error:

django.db.utils.OperationalError: (1267, "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")

Any advice welcome. Thanks!


Solution

  • In your shared_settings.py file try the following:

    DATABASES = {
        "default": {
            "NAME": "DBNAME",
            "ENGINE": "django.db.backends.mysql",
            ...
            "OPTIONS": {"charset": "utf8mb4"}
            # ^ Set the options
        }
    }