1. 程式人生 > 其它 >Django開發填坑之路---Sqlite3更換為Postgres

Django開發填坑之路---Sqlite3更換為Postgres

技術標籤:經驗分享pythondjango

資料庫替換(sqlite3 -> postgres)

背景
初期開發方便,沒有考慮資料庫限制,後期內部系統資料量到達一定量級後需要更換資料庫,且需保持資料遷移。

注意事項:

  1. 需在專案的執行環境(venv)下執行操作
  2. 專案需暫停使用(不要再有資料變化)
  3. 按文章內容 順序執行
  • 基於sqlite3配置的情況下匯出資料
  1. settings配置

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

    python manage.py dumpdata > xxx.json
    (如果有app下migrations 和 django_migrations 表資料不一致時,有較大概率出現問題,需要自己處理下欄位和同步記錄一致問題。語法略,常用 --exclude --indent)

  • 安裝配置postgres資料庫(安裝略)
    • 安裝略(資料庫、django外掛庫postgresql_psycopg2)

    • 建立資料庫

      # 進入postgres
      su - postgres
      
      # 建立使用者
      createuser --interactive -P
      
      # 使用者名稱、密碼
      core_django_test
      xxxxx
      # 是否超級使用者
      y/n
      
      # 建立資料庫db_core
      createdb --owner core_django_test db_core_test
      
      #退出
      logout 
      
    • 檢視資料庫

      # 進入dbshell
      python manage.py dbshell
      
      # 檢視當前資料庫資訊
      \l
      
      

    在這裡插入圖片描述

  • 修改settings檔案資料庫配置
    # DATABASES = {
    #     'default': {
    #         'ENGINE': 'django.db.backends.sqlite3',
    #         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #     }
    # }
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'db_core_test',
            'USER': 'core_django_test',
            'PASSWORD': 'kI6FCvldcEqQ8bho2qj7',
            'HOST': 'localhost',
            'PORT': '',
        }
    }
    
  • 匯入資料
    • 同步資料庫

      # migrations、migrate
      python manage.py migrate 
      python manage.py migrate --run-syncdb
      
    • 匯入資料

      python manage.py loaddata xxx.json

    • 大概率報錯問題解決方案

      django.db.utils.DataError: 
              Problem installing fixture '/var/www/core/1510.json': Could not load interview.SingleChoiceQuestion(pk=71): value too long for type character varying(120)
      

      (長度問題,sqlite3資料檢查不嚴格,max_lenth=10, 也可以儲存超過10的內容)

      解決辦法:
      重新修改報錯位置的欄位長度,後同步資料庫,makemigrations、migrate

      django.db.utils.IntegrityError: Problem installing fixture '/var/www/core/1510.json': Could not load contenttypes.ContentType(pk=16): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq"
               DETAIL:  Key (app_label, model)=(book, group) already exists. 
      

      (content_type特點,預設已儲存有 表-model,model-field資訊,需要先刪除,再匯入資料。

      ​ 注意,每次有migrations、migrate同步操作都需要執行下面的操作)

      解決辦法:

      # 進入shell模式
      python3 manage.py shell
      
      #  執行刪除命令
      from django.contrib.contenttypes.models import ContentType
      ContentType.objects.all().delete()
      
      # 完成退出
      quit()