Change the default database to mysql in Django

Keywords: Python MySQL Database Django pip

In Django, sqlite3 database is used by default. Today, I studied how to change it into a common mysql database.

Because the project uses python3, and MySQL DB does not support the version of python3, if you use the version of python3.x, PIP install MySQL DB will report an error.

Later, through Google, it was found that pymysql could be used instead of MySQL dB

1 add the following code to the "init. Py" file in the root directory of the project:

import pymysql
pymysql.install_as_MySQLdb()

2. Use mysqlclient instead of MySQLdb. The installation method is as follows:

pip install mysqlclient

3. Change the configuration of the database in the project setting.py to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'username',
        'PASSWORD': 'passwd',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}

Finally, Django will automatically create the corresponding tables in the database through the python manage.py migrate command

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying polls.0001_initial... OK
  Applying sessions.0001_initial... OK

5 when creating the admin user, the following error was encountered

python manage.py createsuperuser
Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually.

Later, I checked that it is because I used git to execute commands and switched to the command line provided by Windows, which can solve the problem!

Posted by sujata_ghosh on Mon, 02 Dec 2019 23:51:06 -0800