Django开发--从sqlite迁移到MySQL

2021年9月20日 16:15 by wst

django

迁移原因

         之前做Django开发,用的是默认数据库,即sqlite。但它不利于迁移,所以想着从sqlite迁移MySQL。中间踩了个不大不小的坑,在此记录,为后来者提供一点经验。

迁移步骤

1. 修改 Django项目 中的 settings.py 中的 DATABASES 参数为如下形式:

# filename: settings.py
# new configuration

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

    'substitute': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname', # mysql数据库的用于存放sqlite数据的 dbname
        'USER': 'username', # mysql数据库中的 USER
        'PASSWORD': 'password',  # mysql数据库 USER 对应的密码
        'HOST': '127.0.0.1',  # 创建mysql用户时,使用此host配置
        'PORT': '3306', # mysql 默认端口
    }
}

 

2. 替换连接MySQL用的库,更改与 settings.py 同级的 __init__.py 文件

# filename: __init__.py

import pymysql
pymysql.install_as_MySQLdb()

 

3. 创建mysql用户,把第一步中添加用户在mysql创建一下

以root用户登录MySQL之后,执行以下命令创建用户:

CREATE DATABASE IF NOT EXISTS dbname DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-- 这里的127.0.0.1要和上文的host配置保持一致
CREATE USER 'username'@'127.0.0.1' IDENTIFIED BY 'password';

GRANT ALL privileges ON dbname.* TO 'username'@'127.0.0.1';

 

4. 将 sqlite数据库中的 模型和迁移数据 同步到 MySQL数据库中,执行如下命令:

python manage.py migrate --database substitute

 

5. 把sqlite中的数据导出到filename.json中;

python manage.py dumpdata  > filename.json # filename为备份导出的文件名

 

6. 把导出的数据filename.jso导入到MySQL中

操作之前把settings.py中的DATABASES配置修改为只用MySQL

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname', # mysql数据库的用于存放sqlite数据的 dbname
        'USER': 'username', # mysql数据库中的 USER
        'PASSWORD': 'password',  # mysql数据库 USER 对应的密码
        'HOST': '127.0.0.1',  # 创建mysql用户时,使用此host配置
        'PORT': '3306', # mysql 默认端口
    }
}

然后执行这个命令:

python manage.py loaddata  filename.json

成功后显示如下:

Installed 41 object(s) from 1 fixture(s)

可能遇到的问题:

错误信息:Could not load contenttypes.ContentType(pk=7): (1062, "Duplicate entry 'official-contactinfo' for key 'django_content_type_app_label_model_76bd3d3b_uniq'")

解决方案:

登录mysql执行以下命令

SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE auth_permission;
TRUNCATE django_content_type;

SET FOREIGN_KEY_CHECKS = 1;

总结

在整个迁移过程中,需要注意:

1. 导出数据时,全部导出;

2. 导入数据时,要提前创建好mysql的用户和库,以及设置删除时不检查主外键关联;

 


Comments(126) Add Your Comment

Lpkbnq
buy atorvastatin generic <a href="https://lipiws.top/">order generic lipitor 20mg</a> atorvastatin 20mg canada
Ubhrcn
cipro 500mg ca - <a href="https://cipropro.top/bactrimos/">how to get trimethoprim without a prescription</a> buy cheap clavulanate
Bzhjtq
buy cipro 500mg online - <a href="https://metroagyl.top/cefaclor/">purchase cephalexin pills</a> buy cheap clavulanate
Cubgmq
ciprofloxacin 500 mg cheap - <a href="https://septrim.top/doryx/">doxycycline canada</a> erythromycin sale
Qjlezi
flagyl 200mg usa - <a href="https://metroagyl.top/">order flagyl 400mg generic</a> azithromycin 500mg generic
Qtsybh
ivermectin 12 mg tablets - <a href="https://keflexin.top/">buy ciplox 500 mg generic</a> sumycin over the counter
Mltyjl
valtrex 500mg canada - <a href="https://gnantiviralp.com/vermox/">cost vermox 100mg</a> buy zovirax cheap
Suowrx
purchase ampicillin online cheap <a href="https://ampiacil.top/">acillin over the counter</a> buy amoxil pills
Diclwe
metronidazole pills - <a href="https://metroagyl.top/azithromycin/">order zithromax 500mg generic</a> azithromycin 500mg usa
Silvxn
brand lasix - <a href="https://antipathogenc.com/minipressm/">buy minipress 1mg online cheap</a> captopril 25mg price
Tzogpx
buy metformin 500mg online - <a href="https://gnantiacidity.com/baycip/">ciprofloxacin 1000mg generic</a> lincomycin 500 mg brand
Mpxbfa
where can i buy zidovudine - <a href="https://canadiangnp.com/epivir/">buy epivir 100 mg pills</a> buy allopurinol 300mg
Vtjnpy
order clozapine for sale - <a href="https://genonlinep.com/altace/">oral tritace</a> buy pepcid 40mg without prescription
Zbzqbs
buy quetiapine 100mg online cheap - <a href="https://gnkantdepres.com/desyrel/">where can i buy desyrel</a> eskalith oral
Hizele
clomipramine pill - <a href="https://antdeponline.com/cymbalta/">cymbalta pills</a> order doxepin 75mg online
Ececgz
purchase hydroxyzine generic - <a href="https://antdepls.com/lexapro/">buy lexapro without prescription</a> order endep 10mg sale
Budgdz
brand clavulanate - <a href="https://atbioinfo.com/septra/">bactrim uk</a> purchase ciprofloxacin without prescription
Vksika
buy amoxil medication - <a href="https://atbioxotc.com/cephalexin/">oral keflex 250mg</a> order cipro 1000mg generic
Sctkeq
cost zithromax 500mg - <a href="https://gncatbp.com/">azithromycin 250mg uk</a> ciplox 500 mg cheap
Rktmhr
cost cleocin - <a href="https://cadbiot.com/cefpodoxime/">purchase vantin online cheap</a> cheap chloramphenicol generic
Chfgog
stromectol uk buy - <a href="https://antibpl.com/ascefaclor/">order cefaclor 250mg online</a> cefaclor 500mg price
Bfxwwb
buy generic ventolin 4mg - <a href="https://antxallergic.com/">order ventolin 4mg inhaler</a> brand theo-24 Cr
Okfqpw
methylprednisolone 8mg otc - <a href="https://ntallegpl.com/loratadine/">loratadine cost</a> astelin sale
Cdrwng
purchase desloratadine for sale - <a href="https://rxtallerg.com/ventolinpill/">albuterol inhalator buy online</a> cheap ventolin
Mhaqev
order micronase 5mg pills - <a href="https://prodeprpl.com/pioglitazone30/">actos 30mg cost</a> dapagliflozin 10 mg tablet
Hnixmu
order glycomet 500mg generic - <a href="https://arxdepress.com/sitagliptin50/">order januvia online cheap</a> precose price
Oqzhne
buy prandin generic - <a href="https://depressinfo.com/jardiance25/">empagliflozin 25mg over the counter</a> buy empagliflozin online cheap
Qkoxwa
rybelsus 14 mg uk - <a href="https://infodeppl.com/glucovance5/">order glucovance online cheap</a> DDAVP over the counter
Yzwtnc
lamisil canada - <a href="https://treatfungusx.com/">order lamisil generic</a> oral griseofulvin
Uytvcw
ketoconazole 200mg us - <a href="https://antifungusrp.com/butenafinecream/">purchase mentax generic</a> order sporanox without prescription
Gcnsfj
order famvir 500mg pill - <a href="https://amvinherpes.com/gnvalaciclovir/">order valcivir 500mg generic</a> order valaciclovir without prescription
Xhuxti
buy lanoxin online - <a href="https://blpressureok.com/avalidemed/">buy avapro 150mg generic</a> buy generic lasix
Njdmmy
lopressor 50mg over the counter - <a href="https://bloodpresspl.com/olmesartan/">buy benicar 10mg sale</a> adalat 30mg over the counter
Eolgtm
buy generic hydrochlorothiazide over the counter - <a href="https://norvapril.com/felodipine/">plendil 10mg uk</a> generic bisoprolol
Btuuzu
nitroglycerin drug - <a href="https://nitroproxl.com/clonidinechlorthalidone/">brand combipres</a> buy generic diovan over the counter
Vbmlpg
zocor toss - <a href="https://canescholest.com/atorvastatin/">atorvastatin circle</a> lipitor feast
Ikznbu
crestor very - <a href="https://antcholesterol.com/pravastatin/">pravachol buy line</a> caduet buy city
Hxljzm
viagra professional online into - <a href="https://edsildps.com/">viagra professional online forever</a> levitra oral jelly breath
Wdwmvd
dapoxetine drug - <a href="https://promedprili.com/viagraplus/">viagra plus sufficient</a> cialis with dapoxetine sheet
Dqjddc
cenforce online around - <a href="https://xcenforcem.com/tadaciptadalafil/">tadacip heavy</a> brand viagra description
Kcxjxn
brand cialis prevent - <a href="https://probrandtad.com/penisole/">penisole monsieur</a> penisole terrible
Ntwmxf
brand cialis major - <a href="https://probrandtad.com/">brand cialis summer</a> penisole wake
Ratffc
cialis soft tabs pills group - <a href="https://supervalip.com/valifonline/">valif pills comment</a> viagra oral jelly folk
Rylxme
cialis soft tabs pills stroke - <a href="https://supervalip.com/cialisoraljelly/">cialis oral jelly pills marriage</a> viagra oral jelly blast
Dkblve
priligy source - <a href="https://promedprili.com/levitrawithdapoxetine/">levitra with dapoxetine impossible</a> cialis with dapoxetine bearer
Fvbcte
cenforce online stagger - <a href="https://xcenforcem.com/cialistadalafil/">cialis daily</a> brand viagra pills several
Jntzse
inhalers for asthma exact - <a href="https://bsasthmaps.com/">asthma treatment murmur</a> asthma treatment dream
Loduvf
acne treatment thought - <a href="https://placnemedx.com/">acne medication angel</a> acne medication thing
Ljfbti
prostatitis medications handle - <a href="https://xprosttreat.com/">pills for treat prostatitis plenty</a> prostatitis treatment ankle
Ngcbnp
treatment for uti gas - <a href="https://amenahealthp.com/">uti antibiotics process</a> uti treatment become
Jusylp
claritin pills thoughtful - <a href="https://clatadine.top/">claritin way</a> loratadine medication president
Hjftaa
valtrex pills confess - <a href="https://gnantiviralp.com/">valacyclovir pills library</a> valtrex online yet
Xfbfob
priligy job - <a href="https://prilixgn.top/">priligy mortal</a> dapoxetine foe
Fboxgw
loratadine view - <a href="https://clatadine.top/">loratadine medication suck</a> loratadine medication dry
Fzhxsw
ascorbic acid planet - <a href="https://ascxacid.com/">ascorbic acid superior</a> ascorbic acid definite
Atvbhk
promethazine comfortable - <a href="https://prohnrg.com/">promethazine blanket</a> promethazine boil
Pikojk
clarithromycin royal - <a href="https://gastropls.com/mesalaminepl/">mesalamine pills interval</a> cytotec pills watch
Cghofv
florinef pills pillar - <a href="https://gastroplusp.com/nexesomeprazole/">nexium pills frantic</a> lansoprazole lend
Iumbrw
aciphex brand - <a href="https://gastrointesl.com/reglanmetoclop/">buy reglan 10mg pill</a> buy motilium 10mg sale
Ibqfcn
buy bisacodyl 5mg generic - <a href="https://gastroinfop.com/loperamide/">purchase imodium online cheap</a> order liv52 10mg pills
Tcniqv
buy hydroquinone cheap - <a href="https://danaterone.shop/">eukroma for sale online</a> buy dydrogesterone 10mg online
Ejzyth
bactrim medication - <a href="https://cotrioxazo.com/">buy cotrimoxazole</a> tobramycin online
Ozctox
griseofulvin where to buy - <a href="https://fulviseoful.com/">order griseofulvin 250mg sale</a> brand gemfibrozil
Sbmdzz
cheap forxiga 10mg - <a href="https://forpaglif.com/">generic forxiga 10 mg</a> buy acarbose without a prescription
Skwbbo
buy cheap dimenhydrinate - <a href="https://bisacolax.com/">how to buy dimenhydrinate</a> actonel price
Zekuwo
pill enalapril - <a href="https://vasolapril.com/">vasotec 10mg tablet</a> generic xalatan
Wnghmj
order etodolac for sale - <a href="https://etodograph.com/">monograph us</a> buy cilostazol pills
Pccgek
order piroxicam 20 mg generic - <a href="https://feldexicam.com/">piroxicam where to buy</a> buy rivastigmine generic
Eeqhjq
buy piracetam 800 mg generic - <a href="https://nootquin.com/praziquantel/">generic praziquantel 600mg</a> sinemet canada
Msdmnk
buy hydroxyurea no prescription - <a href="https://hydroydrinfo.com/">hydroxyurea generic</a> order robaxin
Rpimce
buy divalproex pill - <a href="https://adepamox.com/">divalproex 500mg ca</a> buy topiramate without a prescription
Oirlcp
norpace brand - <a href="https://anorpica.com/lamivudine/">buy lamivudine 100mg sale</a> thorazine online buy
Asomyp
buy aldactone without prescription - <a href="https://aldantinep.com/phenytoin/">phenytoin 100mg uk</a> revia 50mg ca
Axxvub
purchase cyclophosphamide sale - <a href="https://cycloxalp.com/dimenhydrinate/">dramamine 50mg generic</a> buy generic vastarel over the counter
Vxnfhr
flexeril 15mg us - <a href="https://abflequine.com/prasugrel/">buy prasugrel 10mg generic</a> buy enalapril 10mg
Gzbdrl
zofran 4mg sale - <a href="https://azofarininfo.com/">how to get ondansetron without a prescription</a> order requip for sale
Vsvbqj
buy ascorbic acid sale - <a href="https://mdacidinfo.com/isosorbidedinitrate/">isordil medication</a> compro generic
Fcrszm
durex gel online buy - <a href="https://xalaplinfo.com/durexcondoms/">buy cheap durex condoms</a> latanoprost canada
Oszsws
rogaine usa - <a href="https://hairlossmedinfo.com/finasteridefinp/">order finpecia online</a> order finpecia for sale
Fwhbzb
arava 20mg usa - <a href="https://infohealthybones.com/risedronate/">purchase actonel online cheap</a> where can i buy cartidin
Ytpmqm
calan 240mg ca - <a href="https://infoheartdisea.com/atenolol/">tenoretic where to buy</a> order tenoretic generic
Fqoenc
buy atenolol without a prescription - <a href="https://heartmedinfox.com/carvedilol/">carvedilol 6.25mg for sale</a> buy coreg 6.25mg online cheap
Xxmffp
buy atorlip generic - <a href="https://infoxheartmed.com/enalapril/">how to get vasotec without a prescription</a> buy nebivolol cheap
Bxijyd
gasex online - <a href="https://herbalinfomez.com/">generic gasex</a> buy diabecon tablets
Mdcuqh
lasuna without prescription - <a href="https://infoherbalmz.com/himcolin/">cheap himcolin generic</a> purchase himcolin pill
Dsiqnc
cheap noroxin - <a href="https://gmenshth.com/">purchase norfloxacin</a> buy confido sale
Saplle
finasteride over the counter - <a href="https://finmenura.com/alfuzosin/">generic uroxatral 10 mg</a> purchase alfuzosin pills
Tyssvw
speman price - <a href="https://spmensht.com/finasteride/">buy fincar generic</a> purchase fincar pill
Yjlelk
hytrin 1mg over the counter - <a href="https://hymenmax.com/">terazosin 5mg without prescription</a> generic priligy
Evmdja
oxcarbazepine 300mg us - <a href="https://trileoxine.com/">order trileptal</a> order levoxyl pill
Ayhkuk
imusporin tubes - <a href="https://asimusxate.com/">where can i buy imusporin</a> oral colchicine 0.5mg
Ogvuum
purchase lactulose for sale - <a href="https://duphalinfo.com/">duphalac online order</a> betahistine price
Ajlmaj
cheap deflazacort pills - <a href="https://lazacort.com/">order calcort sale</a> buy alphagan generic
Vfbpub
buy besifloxacin generic - <a href="https://besifxcist.com/">purchase besivance generic</a> order generic sildamax
Kcdiii
neurontin usa - <a href="https://aneutrin.com/sulfasalazine/">order sulfasalazine 500mg generic</a> azulfidine 500 mg without prescription
Yorjxa
benemid order online - <a href="https://bendoltol.com/">benemid price</a> carbamazepine online
Ylvgyu
celebrex 200mg usa - <a href="https://celespas.com/indomethacin/">order indocin sale</a> indomethacin 75mg pills
Pupyet
mebeverine cheap - <a href="https://coloxia.com/etoricoxib/">etoricoxib 60mg pill</a> buy cilostazol 100mg generic
Atqgvr
buy voltaren 50mg without prescription - <a href="https://dicloltarin.com/aspirin/">order generic aspirin</a> buy cheap aspirin
Yylwot
cheap rumalaya - <a href="https://rumaxtol.com/shallaki/">shallaki order</a> purchase amitriptyline online cheap
Gtotwq
mestinon 60mg cost - <a href="https://mestonsx.com/asumatriptan/">purchase sumatriptan without prescription</a> buy azathioprine 25mg generic
Gupesc
cheap diclofenac sale - <a href="https://vovetosa.com/animodipine/">order nimotop for sale</a> nimodipine tablets
Lgtxpq
brand baclofen 25mg - <a href="https://baclion.com/nspiroxicam/">order piroxicam online</a> order feldene for sale
Lmsddn
buy meloxicam 15mg generic - <a href="https://meloxiptan.com/rtrizatriptan/">toradol over the counter</a> buy ketorolac tablets
Ygtscp
buy cyproheptadine 4 mg pill - <a href="https://periheptadn.com/aszanaflex/">buy zanaflex tablets</a> tizanidine 2mg usa
Dmspyq
trihexyphenidyl without prescription - <a href="https://voltapll.com.com/">artane pills</a> where can i buy voltaren gel
Nttjsi
order cefdinir 300 mg for sale - <a href="https://omnixcin.com/">omnicef online</a> clindamycin cost
Funmhv
purchase absorica sale - <a href="https://aisotane.com/asdeltasone/">deltasone 5mg canada</a> deltasone 10mg without prescription
Aalaqq
order generic prednisone - <a href="https://apreplson.com/">buy prednisone 5mg</a> buy generic zovirax for sale
Boyyda
cheap acticin - <a href="https://actizacs.com/">buy acticin online cheap</a> purchase tretinoin generic
Zvpmql
how to get betamethasone without a prescription - <a href="https://betnoson.com/">betamethasone 20 gm uk</a> buy benoquin without a prescription
Exxhky
cheap metronidazole 200mg - <a href="https://ametronles.com/">buy flagyl pill</a> cenforce medication
Gtigbs
cleocin 300mg cheap - <a href="https://indometnp.com/">indomethacin 50mg brand</a> indocin 50mg for sale
Lyklhf
hyzaar oral - <a href="https://cozartan.com/">losartan over the counter</a> order keflex 250mg without prescription
Zwvrdd
how to get eurax without a prescription - <a href="https://aeuracream.com/caczone/">buy aczone no prescription</a> generic aczone
Tmivdq
brand provigil - <a href="https://sleepagil.com/melatonin/">generic melatonin 3mg</a> order meloset 3mg
Vthpuv
order capecitabine 500mg - <a href="https://xelocap.com/mefenamicacid/">cheap ponstel</a> purchase danocrine sale
Byuyqd
buy progesterone 100mg online - <a href="https://apromid.com/">prometrium 100mg usa</a> fertomid generic
Ykybab
generic fosamax 35mg - <a href="https://pilaxmax.com/tamoxifen/">nolvadex price</a> medroxyprogesterone uk
Zqpvat
order aygestin 5mg sale - <a href="https://norethgep.com/lumigan/">buy cheap lumigan</a> purchase yasmin pills
Cwzlft
estrace 2mg usa - <a href="https://festrolp.com/ginette-35/">buy generic ginette 35 online</a> cost anastrozole 1mg
Wmquwo
cabergoline 0.25mg tablet - <a href="https://adostilin.com/premarin/">premarin brand</a> cheap alesse generic
Hydbcn
プレドニン - 5mg - <a href="https://jpaonlinep.com/jamoxicillin/">アモキシル通販 安全</a> アジスロマイシン 副作用
Zinxzf
正規品シルデナフィル錠の正しい処方 - <a href="https://jpedpharm.com/tadalafil/">タダラフィル は通販での購</a> シアリスの購入
Btduun
プレドニン 値段 - <a href="https://jpanfarap.com/">プレドニンジェネリック 通販</a> アキュテイン通販 安全
Lmzloi
eriacta gift - <a href="https://eriagra.com/szenegrag/">zenegra pills cough</a> forzest apprehension