在做migrations的時候,偶爾會出現出錯。
在已有數據的表中新增字段時,會彈出下面的信息
運行這個命令時
python manage.py makemigrations
Tracking file by folder pattern: migrations
It is impossible to add a non-nullable field ‘example’ to book without specifying a default. This is because 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 manually define a default value in models.py.
Select an option:
解決方案:
選擇1
之后會彈出
Please enter the default value as valid Python.
The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value.
Type ‘exit’ to exit this prompt
輸入, 必須加雙引號
"1"
migrate 無法生成表
運行這個命令時
python manage.py migrate
會出現這種結果
Operations to perform:Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:No migrations to apply.
出現無法生成表的原因是,去到 django_migrations 表里查看,就能知道之前已經創建了表。所以得在該表用sql語句來刪除對應的app數據。
最后運行下面兩個命令
python manage.py makemigrationspython manage.py migrate
這樣就可以創建表了。
點個贊唄~