1. 程式人生 > >Django 常見錯誤記錄

Django 常見錯誤記錄

資料庫問題

1. 配置問題

raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.7 or newer is required; you have 0.7.10.None.

解決辦法:

找到 /home/python/.virtualenvs/py3/lib/python3.5/site-packages/django/db/backends/mysql/base.py

base.py 檔案

將檔案中的如下程式碼註釋即可:

if version < (1, 3, 7):
  raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % Database.__version__) 

2. 資料庫遷移問題

錯誤

1. 外來鍵設定預設值

You are trying to add a non-nullable field 'stage' to course without a default; we can't do that (
the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:

解決辦法:

設定一個預設值,完成遷移後在模型中刪除原來新增的預設值,並且在0001——initial.py中刪除預設值

再執行python manage.py migrate 即可成功

2. 資料庫遷移時報表已經存在

raise errorclass(errno, errval)
django.db.utils.InternalError: (1050, "Table 'user_operation_coursecomments' already exists")

解決辦法:

python manage.py migrate users --fake

其中 users 是自己的子應用名稱

或者: 將已經存在的這個表刪除,再 migrate即可

3. 查詢結果集排序造成的問題

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'courses.models.Video'> QuerySet.
  paginator = self.django_paginator_class(queryset, page_size)

解決辦法:

  1. queryset = Video.objects.all().order_by(‘id’) 將查詢結果集排序
  2. class Meta:
    ​ ordering = [’-id’]
    ​ 加入ordering 排序欄位

4. 錯誤提示如下:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration user_operation.0001_initial is applied before its dependency sketch.0001_initial on database 'default'.

解決辦法:

將之前遷移生成的表全部刪掉(有auth_user表則保留),再重新開始資料庫遷移操作

python manage.py makemigrations

python manage.py migrate

大功告成!!!

後續持續更新!!!