I have a Cloud SQL database running on MySQL 8.0.31. Now, I have a Django 5.1 project that I want to connect the database with (with root permissions). However, whenever I run any python manage.py <django-script-here> (inspectdb, runserver, showmigrations, etc.) command, it results in an error saying
django.db.utils.OperationalError: (2013, 'Lost connection to server during query')
I’m pretty sure its a Django issue because I can connect to the database through MySQLWorkbench 8.0.22, and I can connect to it locally by using the mysql.connector library.
So, I thought it was version problems but I checked the package versions within my virtual environment and they are all compatible with official documentation to back it up (i.e MySQL 8.0.31 works with Django 5.1).
The answer was a very easy fix…. and I didn’t even solve it, so shoutout to my coworker!
So I had my settings.py DATABASES section set up like this:
DATABASES = {
'default:': {
'ENGINE': 'django.db.backends.mysql',
'NAME': ...,
'HOST': ...,
'PORT': ...,
'USER': ...,
'PASSWORD': ...,
}
}
You should change 'django.db.backends.mysql'
to 'mysql.connector.django'
.
Also run pip install mysql-connector-python
My coworker just solved it through trial and error, but still, it’s frustrating that even if you follow the official documentation of Django, MySQL, Cloud SQL, etc. it won’t work and you are expected to troubleshoot from the start.
2