日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Django切換數據庫和遷移數據詳解_python

作者:程序設計實驗室 ? 更新時間: 2022-12-11 編程語言

前言

今天來分享一下 Django 項目切換數據庫和遷移數據的方案,網絡上找到的文章方法不一,且使用中容易遇到各類報錯,本文根據 Django 官方文檔和工作中的經驗,穩定可靠,在博客中長期更新~

如果你遇到同樣的問題,閱讀本文應該能得到比較好的解決方案。

基本步驟

Django 默認使用 SQLite 數據庫方便開發,同時其 ORM 支持多種數據庫,只要安裝對應的驅動就行。

切換數據庫一般是將開發環境的 SQLite 切換到 MySQL (MariaDB) 或 PostgreSql ,本文只測試了從 SQLite 到 MySQL / PostgreSQL,同理,其他切換路徑也是可以的。

數據庫的表結構沒啥問題,使用 Django 的 migrate 功能就行了

關鍵在于數據遷移,可以使用 Navicat 之類的數據庫工具進行數據同步,但往往會因為表之間的約束關系導致同步失敗(要求按特定順序導入數據)。

所以最好的方法是使用 Django 的?dumpdata?功能,將數據庫導出為 json 或 xml 文件,然后切換數據庫再導入。

步驟如下:

  • 導出原有數據:?python manage.py dumpdata -o db.json
  • 在目標數據庫(MySQL / PostgreSql)里創建一個空的庫
  • 在?settings.py?里切換到新的數據庫
  • 建立新的數據庫表結構?python manage.py migrate
  • 導入原有數據:?python manage.py loaddata db.json

搞定~

附上幾種數據庫配置,方便使用

db_config = {
    'sqlite': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'OPTIONS': {
            'timeout': 20,
        }
    },
    'pgsql': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '數據庫名稱',
        'USER': '用戶名',
        'PASSWORD': '密碼',
        'HOST': '數據庫服務器地址',
        'PORT': 5432,
    },
    'mysql': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '數據庫名稱',
        'USER': '用戶名',
        'PASSWORD': '密碼',
        'HOST': '數據庫服務器地址',
        'PORT': 3306,
    }
}
# 這里可以方便切換不同數據庫
DATABASES = {'default': db_config['pgsql']}

其中:

  • MySQL 需要安裝?mysqlclient?包
  • PostgreSql 需要安裝?psycopg2?

然后,事情往往沒有這么簡單和順利,導出導入的過程中可能會遇到一些問題,請繼續看~

導出報錯

報錯信息

CommandError: Unable to serialize database: 'gbk' codec can't encode character '\u30fb' in position 4: illegal multibyte sequence

原因跟編碼有關

解決方法

使用 Python 的 UTF-8 模式導出數據就沒問題

用這個命令導出文件

(不導出?auth.permission?和?contenttypes?,這倆在?migrate?時會自動生成,這樣避免了導入原有數據時沖突)

python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json

或者

python -Xutf8 manage.py dumpdata -o db.json

導入過程出錯解決

報錯1: Duplicate entry

報錯信息

django.db.utils.IntegrityError: Problem installing fixture 'db.json'  Could not load contenttypes.ContentType(pk=15): (1062, "Duplicate entry 'xxx' for key 'django_content_type.django_content_type_app_label_model_76bd3d3b_uniq'")

解決方法一: 重新導出數據

加上這倆參數

  • --natural-primary: Omits the primary key in the serialized data of this object since it can be calculated during deserialization.
  • --natural-foreign: Uses the natural_key() model method to serialize any foreign key and many-to-many relationship to objects of the type that defines the method.

作用是導出的時候去除一些約束,導入時會自動處理,減少導入時因為表之間約束關系的問題

python3 manage.py dumpdata --natural-primary --natural-foreign -o db.json

解決方法二: 刪除?content_type?數據

另一種思路,把?migrate?過程產生的初始化數據刪了,避免導入時和原有數據沖突

先進入 python shell

python3 manage.py shell

輸入以下Python代碼執行

from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()

報錯2: 編碼錯誤

報錯信息

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

解決方法一: 使用 Python 的 UTF8 模式(推薦)

在導入命令前面加上?-Xutf8?參數

python -Xutf8 manage.py loaddata db.json

解決方案二: 魔改 Django 代碼

能用,但不推薦,實在沒辦法再來試這個方法

修改文件

lib\site-packages\django\core\serializers\json.py

在?Deserializer?方法中找到這行代碼

stream_or_string = stream_or_string.decode()

改成這樣

stream_or_string = stream_or_string.decode('UTF-16')

再進行導入操作

參考資料

  • https://docs.djangoproject.com/en/4.1/ref/django-admin/
  • https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/
  • https://javaatpoint.com/solved-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-invalid-start-byte/
  • https://counter2015.com/2020/01/15/django-migration-sqlite-to-postgre/
  • https://stackoverflow.com/questions/64457733/django-dumpdata-fails-on-special-characters

原文鏈接:https://www.cnblogs.com/deali/p/16884908.html

欄目分類
最近更新