Home Backend Development Python Tutorial 将Django使用的数据库从MySQL迁移到PostgreSQL的教程

将Django使用的数据库从MySQL迁移到PostgreSQL的教程

Jun 10, 2016 pm 03:15 PM
django mysql postgresql

我们已对 Django1.6 app完成了数据库从mysql到PostgreSQL的迁移,如果你的环境很干净,这个过程就会很简单,只要允许syncdb 或者 migrate创建表,truncating表中的数据,然后运行dumpdata 和loaddatamanagement命令就完成了。
第一步,在你的PostgreSQL数据库中创建一个空的实例:
 

CREATE DATABASE dbname OWNER rolename;
Copy after login

第二步,在你的Django中给创建的数据库加上配置

在setting.py 中,我们这样配置:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'dbname',
    'USER': 'dbuser',
    'PASSWORD': 'dbpass',
    'HOST': 'mysql.example.com',
    'PORT': '',
  },
  'postgresql': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'dbname',
    'USER': 'dbuser',
    'PASSWORD': 'dbpass',
    'HOST': 'postgresql.example.com',
    'PORT': '',
  }
}
Copy after login

这样我们就指定了以后名称操作的是哪个数据库。
第三步,在PostgreSQL实例中创建表

python manage.py syncdb --migrate --no-initial-data --database=postgresql
Copy after login

在PostgreSQL中运行syncdb 和 migrations,这个过程并没有初始数据。
第四步,truncate新创建的表

尽管我们在先前的步骤中指定了 –no-initial-data ,为了防止在迁移过程中用户的自定义数据在未知情况下加入了表中,我们最好还是truncate一下新建的表,我们可以生成一个SQL脚本,运行:

python manage.py sqlflush --database=postgresql

Copy after login

第五步,从mysql中备份数据到JSON 文件中

Django 有一个dumpdata命令,用它可以生成一个数据库无关的备份,默认格式是JSON。

python manage.py dumpdata --all --natural --indent=4 > dbname.json
Copy after login

这里的 -all 参数是为了确保你在导出数据的过程中有可能有你自己的过滤和修改数据的需求,-natural 参数告诉Django使用natural keys(如果可用的话) –indent 参数是为了使输出更加可读。

你也许想只导出特定的apps里的数据,或者只导出一个celery logs ,这样的话,你就可以使用 –exclude参数,例如:

python manage.py dumpdata --all --natural --exclude=djcelery --exclude=search.SearchLog --indent=4 > dbname.json
Copy after login

第六步,加载JSON数据到PostgreSQL数据库中

python manage.py loaddata dbname.json --database=postgresql
Copy after login

基本上迁移的过程就结束了,现在你只要修改一下你的数据库配置,然后是PostgerSQL成为默认的数据库。

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'dbname',
    'USER': 'dbuser',
    'PASSWORD': 'dbpass',
    'HOST': 'postgresql.example.com',
    'PORT': '',
  }
}
Copy after login

在我们的情况下,我们的数据库不是很干净,我们的数据库是给一个PHP的遗留代码创建的,我们现在还在一步步摆脱它,我们有一些Django之外的数据库,并且都在被程序使用,为了把这些迁移到PostgreSQL中,我使用了这个工具,过程还是简单一些。
注意事项
Django 信号

你可能想禁止这些,当一个数据库记录创建的时候,你的程序可能就会发送给你的用过邮件,为了不打扰它们,在加载数据的时候,你需要保证它们被禁止了,Here's one way to handle this 这里我们使用了检测器保证信号不会别触发。
约束(像非空,unique 和外键)

我们的数据库迁移过程碰到了很多这种问题,比如一个外键约束,但是其他的一个表不存在了,有一下空置的记录,但是模型定义中不允许,比如复制的过程中存在unique约束,这些都需要手动干预,我必须使用SQL语句清除掉这些,Dumpdata 和loaddata 将会检测到这些,所以你的数据库必须是一个干净的一致的状态。

主键的硬编码

这很痛苦,因为在我们的测试 suite中,到处都是主键的硬编码,所以很多测试到失败了,因为使用PostgreSQL 处理的序列的方法和mysql不太一样,我必须手动修改700多个测试用例,大都是很简单的修改但是很消耗时间。

原生SQL语句

幸运的是,我们只有一处使用了原生sql语句,有些mysql中的函数在PostgreSQL中不适用,我们只用修改为在PostgreSQl中相同功能的函数就可以了。

大小写敏感

字符串比较在PostgreSQL中是大小写敏感的,但是在Mysql中不是,我在迁移非Django数据表过程中也遇到了一些问题,索引创建的时候,命令需要id,但是字段的名字是Id(字母I),我只要重命名为id就可以了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles