How Django converts SQLite database to Mysql database

Most novices use the SQLite database by default when they first learn Django development. When deploying online, most of them use Mysql. So how should we migrate the database from SQLite to Mysql?

Previously, we used the SQLite database by default. After we completed the development, there are a lot of data in it. If we want to convert to a Mysql database, we must first export the old data from SQLite, and then import it into the new Mysql database.

1. SQLite export data

Before exporting, let’s make sure that the settins.py database configuration option still uses the SQLite configuration. If it has been modified, please modify it back first:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Then enter in the CMD command line:

python manage.py dumpdata > data.json

This will export the data to the data.json file in the root directory of the Django project.

2. MySQL imports the
same data, first change the Django database configuration to MySQL:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '你的数据库名',
        'USER': '你的MySQL用户名',
        'PASSWORD': '你的密码',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

First find the migrations folder corresponding to the data table, keep __pycache__ and  __init__.py file, and delete the others.

Then execute the following line of command first:

python manage.py makemigrations

Then execute the following line of command:

python manage.py migrate

Then enter in the CMD command line:

python manage.py loaddata data.json

Run the project again and find that it runs successfully

Notice:

Make sure that the Mysql user table is empty. If you have migrated data to Mysql before, errors may occur. Pay attention to the error message reported when something goes wrong. If you are prompted that there are duplicate primary keys, you need to delete the data first. These data are generated when the migration file is applied to the MySQL database, and are generally content_type related tables.

Enter MySQL and execute the following SQL statement:

use 你的数据库名;
delete from auth_permission;
delete from django_content_type;

After deleting the data, execute the import command again. Basically, the inability to import data is caused by the existence of data in MySQL.

Guess you like

Origin blog.csdn.net/muzihuaner/article/details/130664972