python - Django 1.7.1 需要字段的默认值 - 但数据库中没有条目。为什么?

标签 python django django-migrations

我遇到了一个奇怪的问题。我在 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 小时后,我放弃了。

最佳答案

迁移系统的设计使得单个迁移可以应用于多个数据库。例如,您可以有一个开发版本、一个暂存版本和一个或多个生产版本。这就是为什么进行迁移与应用迁移是截然不同的步骤,以及为什么makemgirations 不能只查看当前事件的数据库来了解它没有任何行。如果您随后尝试将迁移应用到执行此操作的数据库会怎样?

您的解决方案很简单:因为没有行,选项 1(对所有现有行设置默认值)根本不会执行任何操作。因此,选择选项 1,以及您喜欢的任何值。

关于python - Django 1.7.1 需要字段的默认值 - 但数据库中没有条目。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26988552/

相关文章:

python - 有没有一种方法可以在不使用 python GIL 的情况下进行序列化/反序列化

python - Django 重复键错误但键不存在

python - django 在生产中不运行特定的迁移(它跳过)

python - 带列表的高效正则表达式

python - int.__mul__ ,执行速度比 operator.mul 慢 2 倍

python - 我的应用程序的管理模板与内置模板的优先级

python - 使用 Django South 处理大型项目的迁移是否安全

python - 为什么 Django Admin 模型页面在成功迁移后引发 FieldDoesNotExist 异常?

python - 通过另外两个列表在python中创建多维列表

python - 从 QuerySet 获取原始 SQL 查询