網(wǎng)站首頁 編程語言 正文
Django切換數(shù)據(jù)庫和遷移數(shù)據(jù)詳解_python
作者:程序設(shè)計(jì)實(shí)驗(yàn)室 ? 更新時(shí)間: 2022-12-11 編程語言前言
今天來分享一下 Django 項(xiàng)目切換數(shù)據(jù)庫和遷移數(shù)據(jù)的方案,網(wǎng)絡(luò)上找到的文章方法不一,且使用中容易遇到各類報(bào)錯(cuò),本文根據(jù) Django 官方文檔和工作中的經(jīng)驗(yàn),穩(wěn)定可靠,在博客中長期更新~
如果你遇到同樣的問題,閱讀本文應(yīng)該能得到比較好的解決方案。
基本步驟
Django 默認(rèn)使用 SQLite 數(shù)據(jù)庫方便開發(fā),同時(shí)其 ORM 支持多種數(shù)據(jù)庫,只要安裝對(duì)應(yīng)的驅(qū)動(dòng)就行。
切換數(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ù)同步,但往往會(huì)因?yàn)楸碇g的約束關(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)建一個(gè)空的庫
- 在?
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)入的過程中可能會(huì)遇到一些問題,請(qǐng)繼續(xù)看~
導(dǎo)出報(bào)錯(cuò)
報(bào)錯(cuò)信息
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ù)就沒問題
用這個(gè)命令導(dǎo)出文件
(不導(dǎo)出?auth.permission
?和?contenttypes
?,這倆在?migrate
?時(shí)會(huì)自動(dòng)生成,這樣避免了導(dǎo)入原有數(shù)據(jù)時(shí)沖突)
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
或者
python -Xutf8 manage.py dumpdata -o db.json
導(dǎo)入過程出錯(cuò)解決
報(bào)錯(cuò)1: Duplicate entry
報(bào)錯(cuò)信息
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)出的時(shí)候去除一些約束,導(dǎo)入時(shí)會(huì)自動(dòng)處理,減少導(dǎo)入時(shí)因?yàn)楸碇g約束關(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í)和原有數(shù)據(jù)沖突
先進(jìn)入 python shell
python3 manage.py shell
輸入以下Python代碼執(zhí)行
from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete()
報(bào)錯(cuò)2: 編碼錯(cuò)誤
報(bào)錯(cuò)信息
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 代碼
能用,但不推薦,實(shí)在沒辦法再來試這個(gè)方法
修改文件
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
原文鏈接:https://www.cnblogs.com/deali/p/16884908.html
相關(guān)推薦
- 2022-03-12 使用xshell連接linux服務(wù)器_Linux
- 2022-08-20 Django細(xì)致講解多對(duì)多使用through自定義中間表方法_python
- 2022-06-15 golang如何用type-switch判斷interface變量的實(shí)際存儲(chǔ)類型_Golang
- 2022-01-22 Redis學(xué)習(xí)之旅--與SpringBoot的結(jié)合
- 2022-12-13 Kubernetes中創(chuàng)建命名空間實(shí)現(xiàn)方法_云其它
- 2022-04-05 Linux環(huán)境 redis 值中文顯示亂碼 解決辦法 --raw參數(shù)
- 2022-12-08 利用C語言編寫一個(gè)無限循環(huán)語句_C 語言
- 2024-01-13 nvm命令
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支