Django切換數(shù)據(jù)庫和遷移數(shù)據(jù)詳解
前言
今天來分享一下 Django 項目切換數(shù)據(jù)庫和遷移數(shù)據(jù)的方案,網(wǎng)絡(luò)上找到的文章方法不一,且使用中容易遇到各類報錯,本文根據(jù) Django 官方文檔和工作中的經(jīng)驗,穩(wěn)定可靠,在博客中長期更新~
如果你遇到同樣的問題,閱讀本文應(yīng)該能得到比較好的解決方案。
基本步驟
Django 默認(rèn)使用 SQLite 數(shù)據(jù)庫方便開發(fā),同時其 ORM 支持多種數(shù)據(jù)庫,只要安裝對應(yīng)的驅(qū)動就行。
切換數(shù)據(jù)庫一般是將開發(fā)環(huán)境的 SQLite 切換到 MySQL (MariaDB) 或 PostgreSql ,本文只測試了從 SQLite 到 MySQL / PostgreSQL,同理,其他切換路徑也是可以的。
數(shù)據(jù)庫的表結(jié)構(gòu)沒啥問題,使用 Django 的 migrate 功能就行了
關(guān)鍵在于數(shù)據(jù)遷移,可以使用 Navicat 之類的數(shù)據(jù)庫工具進(jìn)行數(shù)據(jù)同步,但往往會因為表之間的約束關(guān)系導(dǎo)致同步失敗(要求按特定順序?qū)霐?shù)據(jù))。
所以最好的方法是使用 Django 的 dumpdata 功能,將數(shù)據(jù)庫導(dǎo)出為 json 或 xml 文件,然后切換數(shù)據(jù)庫再導(dǎo)入。
步驟如下:
- 導(dǎo)出原有數(shù)據(jù):
python manage.py dumpdata -o db.json - 在目標(biāo)數(shù)據(jù)庫(MySQL / PostgreSql)里創(chuàng)建一個空的庫
- 在
settings.py里切換到新的數(shù)據(jù)庫 - 建立新的數(shù)據(jù)庫表結(jié)構(gòu)
python manage.py migrate - 導(dǎo)入原有數(shù)據(jù):
python manage.py loaddata db.json
搞定~
附上幾種數(shù)據(jù)庫配置,方便使用
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': '數(shù)據(jù)庫名稱',
'USER': '用戶名',
'PASSWORD': '密碼',
'HOST': '數(shù)據(jù)庫服務(wù)器地址',
'PORT': 5432,
},
'mysql': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '數(shù)據(jù)庫名稱',
'USER': '用戶名',
'PASSWORD': '密碼',
'HOST': '數(shù)據(jù)庫服務(wù)器地址',
'PORT': 3306,
}
}
# 這里可以方便切換不同數(shù)據(jù)庫
DATABASES = {'default': db_config['pgsql']}
其中:
- MySQL 需要安裝
mysqlclient包 - PostgreSql 需要安裝
psycopg2包
然后,事情往往沒有這么簡單和順利,導(dǎo)出導(dǎo)入的過程中可能會遇到一些問題,請繼續(xù)看~
導(dǎo)出報錯
報錯信息
CommandError: Unable to serialize database: 'gbk' codec can't encode character '\u30fb' in position 4: illegal multibyte sequence
原因跟編碼有關(guān)
解決方法
使用 Python 的 UTF-8 模式導(dǎo)出數(shù)據(jù)就沒問題
用這個命令導(dǎo)出文件
(不導(dǎo)出 auth.permission 和 contenttypes ,這倆在 migrate 時會自動生成,這樣避免了導(dǎo)入原有數(shù)據(jù)時沖突)
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
或者
python -Xutf8 manage.py dumpdata -o db.json
導(dǎo)入過程出錯解決
報錯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'")
解決方法一: 重新導(dǎo)出數(shù)據(jù)
加上這倆參數(shù)
--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.
作用是導(dǎo)出的時候去除一些約束,導(dǎo)入時會自動處理,減少導(dǎo)入時因為表之間約束關(guān)系的問題
python3 manage.py dumpdata --natural-primary --natural-foreign -o db.json
解決方法二: 刪除 content_type 數(shù)據(jù)
另一種思路,把 migrate 過程產(chǎn)生的初始化數(shù)據(jù)刪了,避免導(dǎo)入時和原有數(shù)據(jù)沖突
先進(jìn)入 python shell
python3 manage.py shell
輸入以下Python代碼執(zhí)行
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 模式(推薦)
在導(dǎo)入命令前面加上 -Xutf8 參數(shù)
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')
再進(jìn)行導(dǎo)入操作
參考資料
- 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
到此這篇關(guān)于Django切換數(shù)據(jù)庫和遷移數(shù)據(jù)詳解的文章就介紹到這了,更多相關(guān)Django切換數(shù)據(jù)庫和遷移數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python numpy數(shù)組中的復(fù)制知識解析
這篇文章主要介紹了python numpy數(shù)組中的復(fù)制知識解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02
python將ip地址轉(zhuǎn)換成整數(shù)的方法
這篇文章主要介紹了python將ip地址轉(zhuǎn)換成整數(shù)的方法,涉及Python針對IP地址的轉(zhuǎn)換技巧,需要的朋友可以參考下2015-03-03
Python控制windows系統(tǒng)音量實現(xiàn)實例
這篇文章主要介紹了Python控制windows系統(tǒng)音量實現(xiàn)實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

