4

每当我尝试在我的一个 Django 项目中使用 South 进行迁移时,我无法弄清楚如何避免此错误:

错误:

为 askbot 运行迁移:

  • 向前迁移到 0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl。

askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl

致命错误 - 以下 SQL 查询失败:ALTER TABLE "tagplus" ADD COLUMN "id" serial NOT >NULL PRIMARY KEY DEFAULT -1; 错误是:为表“tagplus”的列“id”指定了多个默认值

迁移错误:>askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl DatabaseError:为表“tagplus”的列“id”指定了多个默认值

迁移文件 0006 代码(部分):

class Migration(SchemaMigration):

def forwards(self, orm):
    # Deleting field 'TagPlus.tag_ptr'
    db.delete_column(u'tagplus', u'tag_ptr_id')

    # Adding field 'TagPlus.id'
    db.add_column(u'tagplus', u'id',
                  self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True),
                  keep_default=False)

    # Adding field 'TagPlus.name'
    db.add_column(u'tagplus', 'name',
                  self.gf('django.db.models.fields.CharField')(default=0, unique=True, max_length=255),
                  keep_default=False)

   

谢谢!

编辑:

我猜这个错误与我在创建迁移文件时被提示的这个选择有关。

 ? The field 'TagPlus.tag_ptr' does not have a default specified, yet is NOT NULL.
 ? Since you are removing this field, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ?  1. Quit now.
 ?  2. Specify a one-off value to use for existing columns now
 ?  3. Disable the backwards migration by raising an exception; you can edit the migration to fix it later
 ? Please select a choice: 

我选择了“指定一次性值”并将此值设置为0

4

2 回答 2

5

反正你是说keep_default=False。所以default=0从你的代码中删除它

   db.add_column(u'tagplus', u'id',
                  self.gf('django.db.models.fields.AutoField')(primary_key=True),
                  keep_default=False)

每个 SQL 应该是(删除NOT NULL

ALTER TABLE tagplus ADD COLUMN id serial PRIMARY KEY

请参阅本文档,其中解释了此错误背后的原因http://www.postgresql.org/docs/8.3/interactive/datatype-numeric.html#DATATYPE-SERIAL

于 2014-05-07T20:37:28.350 回答
2

有两点需要注意:

  1. 如果您之前没有手动设置过,Django 将使用 'id' 作为默认主键,请参见此处

  2. Postgres 并没有真正的“串行”类型。要解决此问题,请尝试替换:

    # Adding field 'TagPlus.id'
    db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)
    

和:

    # Adding field 'TagPlus.id'
    if 'postgres' in db.backend_name.lower():
        db.execute("CREATE SEQUENCE tagplus_id_seq")
        db.execute("SELECT setval('tagplus_id_seq', (SELECT MAX(id) FROM tagplus))")
        db.execute("ALTER TABLE tagplus ADD COLUMN id SET DEFAULT nextval('tagplus_id_seq'::regclass)")
        db.execute("ALTER SEQUENCE tagplus_id_seq OWNED BY tagplus.id")
    else:
        db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)
于 2014-05-25T16:05:31.040 回答