【问题标题】:How to create a migration after adding an hstore field? (django-hstore vs. South)添加 hstore 字段后如何创建迁移? (django-hstore vs. South)
【发布时间】:2013-04-09 17:23:19
【问题描述】:

我在数据库中有一个现有模型。我想用一个 hstore 字段来增强它。我安装了hstore Postgres扩展,django-hstore app,在django项目中更改了相应的设置:

SOUTH_DATABASE_ADAPTERS = {'default': 'south.db.postgresql_psycopg2'}
DATABASES = {
    'default': {
        'ENGINE': 'django_hstore.postgresql_psycopg2',
        ...

我检查了 django 应用程序是否适用于新设置——确实如此。所以我将新字段添加到其中一个模型中:

data = hstore.DictionaryField(db_index=True)

下一步:数据库迁移。在这里我迷路了。在尝试为新字段创建迁移时,我得到了这个:

The field 'Project.data' does not have a default specified, yet is NOT NULL.
Since you are adding this field, you MUST specify a default
value to use for existing rows. Would you like to:
 1. Quit now, and add a default to the field in models.py
 2. Specify a one-off value to use for existing columns now

我在这里做什么?我错过了什么?我没有在任何 django-hstore 相关文章中找到对默认值(或 null=True)的任何引用。

【问题讨论】:

    标签: python django postgresql django-south hstore


    【解决方案1】:

    此消息通常在 South 尝试更新数据库中的模型并在您尝试修改的表上找到现有行时出现。为了继续并在数据库上创建新字段,您必须为要迁移的表的现有行指定一个值。我通常做什么,如果是开发阶段,我会选择选项 2 并将值设置为 0,{} 空 dict,甚至 NULL,具体取决于字段类型。

    【讨论】:

    • 是的,我最初尝试使用 {},但在应用迁移时它中断了。恐怕 hstore.DictionaryField 是完全不同的野兽。
    • 问题可能是索引标志,我认为数据库将字典作为索引处理很复杂。
    • 其实一开始我试过不带它,结果发现它是 hstore DictionaryField 的默认设置。
    【解决方案2】:

    正如已经提到的,当您点击 2 时,您可以选择一个空字符串 ("") 或按照它的存储方式填充该字段:

    ? The field 'MyModel.data' does not have a default specified, yet is NOT NULL.
    ? Since you are adding this field, you MUST specify a default
    ? value to use for existing rows. Would you like to:
    ?  1. Quit now, and add a default to the field in models.py
    ?  2. Specify a one-off value to use for existing columns now
    ? Please select a choice: 2
    ? Please enter Python code for your one-off default value.
    ? The datetime module is available, so you can do e.g. datetime.date.today()
    >>> "foo=>bar,foo2=>bar2"
    

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2012-05-19
      • 2016-12-16
      • 2016-01-06
      • 2016-10-25
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      相关资源
      最近更新 更多