【问题标题】:Changing Django development Database from the default SQLite to PostgreSQL将 Django 开发数据库从默认 SQLite 更改为 PostgreSQL
【发布时间】:2018-10-23 16:18:54
【问题描述】:

从默认 SQLite 数据库迁移到 Postgres 数据库需要采取哪些步骤?

我这样做是为了让我的本地开发环境尽可能靠近我的实时服务器(使用 postrgres)。

或者说本地开发使用 SQLite 有什么原因吗?本地开发不建议使用 Postgres 吗?

【问题讨论】:

  • 除非你有理由不这样做,否则它只会在 SQLite3 上提供一个更“精简”的开发环境。如果您确保不会在开发和发布之间混淆settings.py,那么您应该是黄金,这就是我做大部分项目的方式。

标签: python django postgresql sqlite


【解决方案1】:

您可以尝试以下步骤:

1.安装psycopg2配置数据库:

pip install psycopg2


2.里面默认settings.py

更改原始值:

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

收件人:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'NAME_OF_DB',
        'USER': 'DB_USER_NAME',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',
        'PORT': 'PORT_NUMBER',
    }
}


3. 迁移数据库:

python manage.py makemigrations
python manage.py migrate


编辑: 感谢@robotHamster 评论。以下是同步现有数据的方法:

先备份数据:

python manage.py dumpdata > datadump.json

更改数据库设置后:

python manage.py loaddata datadump.json


来源:What's the best way to migrate a Django DB from SQLite to MySQL?

【讨论】:

  • 结合this gist你应该也能保留你的数据
【解决方案2】:

当您更改数据库时,您可能会得到一个 UNICODEERRO:'utf-8'

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

在浪费了 5 天多之后,我终于得到了解决方案。你永远不会在互联网上得到那个准确的错误,我自己想出来的。

python manage.py dumpdata > datadump.json

然后根据您想要的数据库更改数据库 settings.py,然后应用以下命令...

python manage.py makemigrations
python manage.py migrate
python manage.py loaddata datadump.json

如果您遇到我之前提到的错误,请按照分步指南进行操作:

1.Install notepad ++
2.open your datadum.json file in notepad++
3.on the bottom right corner you will get the encoding will be anything else than utf-8
4.on the top bar select encoding to UTF-8

你很高兴……然后再来一次

python manage.py load data datadump.json

为此我受了很多苦...所以请点赞,分享也很受欢迎。 谢谢! 如需更多信息,您可以观看此视频:https://youtu.be/RBtEr3TXNwg

【讨论】:

【解决方案3】:

这是来自Django Girls的关于如何做到这一点的精彩教程

它会显示安装以及 settings.py 中所需的更改。

【讨论】:

    【解决方案4】:

    希望我没有迟到。因此,根据我的经验,如果您的 sqlite 数据库中已经有数据,您可能会面临一些挑战,因为 sqlite 中的某些字段与 postgres 中的字段不直接匹配。例如日期时间和布尔字段。

    我找到了一个帮助我做到这一点的库:

    https://github.com/Hitman23/pgloader

    库会进行任何需要的转换。

    【讨论】:

      猜你喜欢
      • 2015-05-03
      • 2012-02-12
      • 2016-03-05
      • 2021-05-21
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多