我遇到了一个奇怪的问题。我在 Mac OS X Yosemite 上使用 Django 1.7.1,并且配置了本地 MySQL 数据库。
通常,我创建一个模型,如果我想添加另一个字段,我只需做一个./manage.py migrate
Django 创建一个新的数据库列。
我正是这样做的。这是我的模型:
from django.db import models
from django.utils.translation import ugettext as _
class Product(models.Model):
CATEGORY_CHOICES = (
('apphosting', _('Application Hosting')),
('webhosting', _('Web Hosting'))
)
category = models.CharField(max_length=25, choices=CATEGORY_CHOICES)
name = models.CharField(max_length=25)
price_monthly = models.FloatField()
def __unicode__(self):
return self.name
请注意我已经添加了该字段price_monthly
。然后,我做了一个./manage.py migrate
:
(mysphere)dmanser@ragamuffin:~/git/mysphere on master [!?]$ ./manage.py migrate
Operations to perform:
Synchronize unmigrated apps: crispy_forms
Apply all migrations: customers, sessions, admin, sites, flatpages, contenttypes, products, auth
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
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.
好吧,我做一个./manage.py makemigrations
,结果是:
(mysphere)dmanser@ragamuffin:~/git/mysphere on master [!?]$ ./manage.py makemigrations
You 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:
奇怪的是,这个模型还没有条目。那么,如果数据库中没有产品,为什么我需要提供默认值呢?
我开始拔掉头发,昨天我尝试了几件事。 3个小时后我放弃了。