Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
How do I set collation_connection in Django?

I put this in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'NAME': 'db',
        'USER': 'root',
        'PASSWORD': '',
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': 'set collation_connection=utf8mb4_unicode_ci',
        },
    },
}

Then I used the shell to check that it worked:

$ ./manage.py shell
>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute("show variables like 'collation_connection'")
>>> print cursor.fetchall()
((u'collation_connection', u'utf8mb4_general_ci'),)

Unfortunately, what I've learned from inspecting my query log is that MySQLdb does this when it connects:

set collation_connection='utf8mb4_unicode_ci'
SET NAMES utf8mb4

That's right. It executes set names after my init command. This sets the collation back to the default.

Omitting the 'charset' option doesn't help. If I do, it will call set names utf8 instead, which is even worse. I tried making the set names command part of my 'init_command' in case it wouldn't clobber my collation if there was nothing to change, but no, it still clobbers it.

I can't fork the Python library MySQLdb because I'm running my app on Google App Engine and MySQLdb is part of App Engine.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I was able to accomplish this by monkey-patching Django:

from django.db.backends.mysql import base
old_get_new_connection = base.DatabaseWrapper.get_new_connection
def get_new_connection(self, conn_params):
  conn = old_get_new_connection(self, conn_params)
  conn.query("set names 'utf8mb4' collate 'utf8mb4_unicode_520_ci'")
  return conn

base.DatabaseWrapper.get_new_connection = get_new_connection

Btw, this patch was necessary to even use the utf8mb4 character set on App Engine because they are using an old version of MySQL Connector C which doesn't support that character set. Without this character set, your app will crash if you attempt to insert any four-byte UTF8 characters, and any existing ones in the database will show up as question marks.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!