How to use MySQL with Django

Dec 13, 2023    |   

Django comes with built-in support for MySQL and MariaDB. It uses a library called mysqlclient to connect to these databases.

When you install mysqlclient, it automatically compiles against either the MariaDB or MySQL client library that you have installed on your system.

However, there are some challenges when compiling the C extension.

An alternative is to use the pymysql library. It is a pure Python DB API driver and does not require C compilation. Pymysql is developed by the same team as mysqlclient and is currently better maintained.

Although Django does not officially support pymysql, it is not difficult to use it.

Step 1: install pymysql

# or pip3 install pymysql
pip install pymysql

Step 2: configure to use pymysql in your settings

import pymysql


pymysql.install_as_MySQLdb()