1. 程式人生 > >Django 資料庫錯誤

Django 資料庫錯誤

django資料庫錯誤相關問題

問題:欄位修改屬性發生錯誤

1>

>python manage.py makemigrationsYou are trying to add a non-nullable field 'price_monthly' to product without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:

{這個可能是之前已建立了表中的一條記錄,之後模型中增加了一個非空的欄位,但是原來已經存在的記錄沒有這個值}

2>

>python manage.py migrate
... ...
raise errorclass(errno, errorvalue)django.db.utils.ProgrammingError: (1146, "Table 'lab_data.bigdata_postgraduate_research_directions' doesn't exist")
{這個是因為在欄位中添加了blank=True或者 null=True引起的}

3>

>python manage.py makemigrations
You are trying to change the nullable field 'job_title' on professor to non-nullable without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Ignore for now, and let me handle existing rows with NULL myself (e.g. adding a RunPython or RunSQL operation in the new migration file before the AlterField operation)
 3) Quit, and let me add a default in models.py
Select an option:
{這個是將模型中的null=True刪除了之後產生的錯誤}

1>原因解釋:

1. The migrations system is designed so that a single migration can be applied to more than one database. For example, you could have a development version, a staging version, and one or more production versions. That's whymaking the migration is a distinct step from applying the migration, and whymakemgirations can't just look at the currently active database to see that it doesn't have any rows. What if you then try to apply the migration to a database that does?

The solution in your case is simple: since there are no rows, option 1 (setting a default on all existing rows) won't do anything at all. So choose option 1, and any value you like.

[Django 1.7.1 requires a Default value for field - but no entry is in database. Why?]

2. Django adds a default "id" field to every model, you don't need an extra "twitbot_id" in your model. If a surrogate primary key is all you need, forget about "twitbot_id" because it will be a duplicate of the auto-generated "id". Seehttps://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields

If you add this and you already have TwitterBot objects in your database you must provide a default value to populate this column for existing rows in the database.

[Can't seem to lose this error: “You are trying to add a non-nullable field”]

3. 如果你跟我一樣是因為之前建好表a後,又建立一個表b作為a的父類,a中只有pass,那麼因為表a已經建立,其中有資料,當a遷移時就會出現新表不能為null且沒有指定預設值時就會出現這種錯誤。

解決方案:

1>在基類b中新增允許為空或者新增預設值,並設定b不建表(meta中的abstract = true)

class Base(models.Model):
'''
    基類
    '''title = models.CharField(max_length=150, null=True)
    content = models.TextField(null=True)
    time_stamp = models.DateTimeField(auto_now_add=True, default=timezone.now())
    link = models.URLField(blank=True, verbose_name='url_link')

    class Meta:
abstract = True
Note:DataTimeField好像與其它的不一樣,不好改!

1>2>3>

刪除所有migrate檔案(不用移除整個資料夾),然後重來

問題:manytomanyfeild沒有預設值


問題:新增元屬性發生錯誤

raise InternalError(errno, errorvalue)
django.db.utils.InternalError: (1017, "Can't find file: '.\\lab_data\\people_patent_prizes.frm' (errno: 2 -No such file or directory)")
{模型類中增加class Meta:db_table='People'使資料庫中對應的表名修改成了People,原來的表間聯絡可能破壞了}
解決方案:

刪除所有migrate檔案(不用移除整個資料夾),然後重來

http://blog.csdn.net/pipisorry/article/details/45727309

問題:表中欄位不存在

"Unknown column 'name' in 'field list'"

django中建立了表professor繼承了表people的欄位,並且在後臺可以看到,但實際在資料庫中不存在(資料庫中查詢可看到)

出現問題原因:

1. model中編輯的欄位沒有在資料庫對應的表裡建立(原因可能是欄位是繼承自父類,出現的什麼問題?)

資料庫中查看錶中的欄位:


2. migration檔案出了什麼問題?導致沒有同步到資料庫(表都沒建立)

解決方案1:

在資料庫中手動新增沒有建立的欄位

alter table bigdata_professor add column name varchar(6);

再次查看錶中欄位:


再次執行django伺服器,後臺新增name欄位時就不會出錯了。

解決方案2:

先刪除整個migrations資料夾,再Python manage.py makemigrations,再python manage.py migrate


這樣表就可以重新建立成功了!(可以查詢到django中新建的表bigdata_professor....)


Note:

1. 成功後最好把之前刪除的資料夾migrations重新建一個(app中的)

2. 只刪除migration檔案可能不會出現這個問題:

No migrations to apply.   Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

我了個去,都不知道為啥migration檔案會出問題,刪除後再操作就沒事了,可能是(在makemigrations)之前先進行了migrate操作?

問題:表不存在或者No migrations to apply

 "Table 'lab_data.bigdata_resdir' doesn't exist"

模型中建立新表後,makemigrations成功,但是migrate出現錯誤:

python manage.py migrate
Operations to ...:
Apply all migrations: ...
No migrations to apply.(即使實際上明明makemigrations成功,並且有許多migrations可以應用)
  Your models have changes that are not yet reflected in a migration, and so won't be applied.  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
按照提示重新makemigration後migration檔案就不會建立新表了,在資料庫中表也的確沒有新建。

原因:

1. Sounds like your initial migration was faked because the table already existed (probably with an outdated schema):

"This will make a new initial migration for your app. Now, when you run migrate,Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied."

Otherwise you would get an no-such-table error.

2. 也可能是之前按照某個說明執行了一次python manage.py migrate --fake導致的。--fake 的含義是不執行該遷移指令碼但是標記該指令碼已經被執行過。導致之後無法正常進行遷移。

解決方案:

方法1.

1> In MySQL Database delete row 'app_name' from the table 'django_migrations'.

開啟mysql command line client, 進入建立好的資料庫use databasename; 查看錶select * from django_migration; 發現將要執行的遷移指令碼的 id 已經新增在表中了,將其刪除即可,即刪除最新一次app_name對就的id行。


2> Delete all migration files in migrations folder.

3> Try again python manage.py makemigrations and python manage.py migrate command.

方法2:

移除整個migrations資料夾,重新makemigrations和migrate。之後就會自動建立了:

方法3:

實在不行,只能drop database,再重新建立了。

問題:外來鍵修改成多對多錯誤

ValueError: Cannot alter field bigdata.Postgraduate.publisher into bigdata.Postgraduate.publisher - they are not compatible types (you cannot alter to or from M2M fields
, or add or remove through= on M2M fields)
{這個錯誤是由將模型Postgraduate中的publisher欄位從ForeignKey修改成ManyToManyField引起的}

解決方案:

刪除所有migrations檔案,重新makemigrations和migrate

資料庫註冊到site管理錯誤

TypeError: __init__() missing 2 required positional arguments : 'model' and 'admin_site'

class DirectionsInline(inlineBase, admin.ModelAdmin):
model = Directions
    inlines = [ImagesInline, ]
admin.site.register(Directions, DirectionsInline)
解決:原因可能是繼承admin.ModelAdmin的類中不能有model = ***

資料庫許可權錯誤

django.db.utils.operationalerror:<1045,"access denied for user [email protected] using password yes>

解決方案1:django setting.py檔案中設定的database使用者名稱或者密碼錯了,修改一下就可以了

或者是django執行專案時用的不是settings.py檔案,這個在os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labsite.settings")中設定

其它方案

django.db.utils.operationalerror:<2003, "can't connect to mysql server on '127.0.0.1'(winerror 10061] No connection could be made because the target machine actively refused it)")

settings.py中設定的host和port如下

'HOST': '127.0.0.1','PORT': '3306'

如改動port為其它,可能導致該問題

其它問題:

2. django.db.utils.ProgrammingError: (1146, "Table 'lab_data.django_migrations' doesn't exist")

3.django.db.utils.InternalError: (1050, "Table '`l ab_data`.`django_migrations`'already exists")

1>兩個模型的資料庫表名設定成一樣的了

class Meta:
db_table = 'WorkExp1'

2>python manage.py migrate --fake

from:http://blog.csdn.net/pipisorry/article/details/45727309