MySQL Connector/Python Developer Guide  /  Connector/Python Other Topics  /  Connector/Python Django Back End

9.2 Connector/Python Django Back End

Connector/Python includes a mysql.connector.django module that provides a Django back end for MySQL. This back end supports new features found as of MySQL 5.6 such as fractional seconds support for temporal data types.

Django Configuration

Django uses a configuration file named settings.py that contains a variable called DATABASES (see https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-DATABASES). To configure Django to use Connector/Python as the MySQL back end, the example found in the Django manual can be used as a basis:

DATABASES = {
    'default': {
        'NAME': 'user_data',
        'ENGINE': 'mysql.connector.django',
        'USER': 'mysql_user',
        'PASSWORD': 'password',
        'OPTIONS': {
          'autocommit': True,
        },
    }
}

It is possible to add more connection arguments using OPTIONS.

Support for MySQL Features

Django can launch the MySQL client application mysql. When the Connector/Python back end does this, it arranges for the sql_mode system variable to be set to TRADITIONAL at startup.

Some MySQL features are enabled depending on the server version. For example, support for fractional seconds precision is enabled when connecting to a server from MySQL 5.6.4 or higher. Django's DateTimeField is stored in a MySQL column defined as DATETIME(6), and TimeField is stored as TIME(6). For more information about fractional seconds support, see Fractional Seconds in Time Values.


User Comments
User comments in this section are, as the name implies, provided by MySQL users. The MySQL documentation team is not responsible for, nor do they endorse, any of the information provided here.
  Posted by Ezequiel Bertti on December 28, 2018
Hi, i made this small wrapper on mysql-connector to pooling work on django backend:

----

from django.conf import settings
from mysql.connector.django.base import DatabaseWrapper as _DatabaseWrapper
from mysql.connector.pooling import MySQLConnectionPool

POOL = {}

class DatabaseWrapper(_DatabaseWrapper):

def get_new_connection(self, conn_params):
if not settings.DATABASE_POOL:
return super().get_new_connection(conn_params)

global pool
if self.alias not in POOL:
POOL[self.alias] = MySQLConnectionPool(
pool_name=self.alias,
pool_size=settings.DATABASE_POOL,
pool_reset_session=True,
**conn_params
)
return POOL[self.alias].get_connection()