0

我一直在使用 Django 项目开发 sqlite3 数据库。我正在将项目移动到使用 Postgres 的生产环境中。我用过 South,所以我的所有迁移都是自动化的。

我在尝试迁移架构时遇到以下错误:

[05/Feb/2013 16:38:31] DEBUG [south:270] execute "ALTER TABLE "frontend_userprofile" ADD COLUMN "id" serial NULL PRIMARY KEY;" with params "[]"
FATAL ERROR - The following SQL query failed: ALTER TABLE "frontend_userprofile" ADD COLUMN "id" serial NULL PRIMARY KEY;
The error was: conflicting NULL/NOT NULL declarations for column "id" of table "frontend_userprofile"

[..]

django.db.utils.DatabaseError: conflicting NULL/NOT NULL declarations for column "id" of table "frontend_userprofile"

这是迁移文件的相关部分:

def forwards(self, orm):
    # Adding field 'UserProfile.id'
    db.add_column('frontend_userprofile', 'id',
                  self.gf('django.db.models.fields.AutoField')(default=None, primary_key=True, null=True),
                  keep_default=False)


    # Changing field 'UserProfile.user'
    db.alter_column('frontend_userprofile', 'user_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True, null=True))

[..]

    'frontend.userprofile': {
        'Meta': {'object_name': 'UserProfile'},
        'company': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['frontend.Company']", 'null': 'True'}),
        'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
        'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'null': 'True'})
    }

和模型:

class UserProfile(models.Model):
    user    = models.OneToOneField(User, null=True, unique=True)
    company = models.ForeignKey(Company, null=True, default=None)

编辑

正如 Jordan 所建议的,您不能同时拥有空主键,因此以下更改可以解决此问题:

    db.add_column('frontend_userprofile', 'id',
                  self.gf('django.db.models.fields.AutoField')(default=None, primary_key=True),
                  keep_default=False)


class UserProfile(models.Model):
    user    = models.OneToOneField(User, unique=True)
    company = models.ForeignKey(Company, null=True, default=None)

但是我在完成迁移时仍然遇到问题:

DEBUG [south:270] execute "ALTER TABLE "frontend_userprofile" ADD COLUMN "id" serial NOT NULL PRIMARY KEY;" with params "[]"
FATAL ERROR - The following SQL query failed: ALTER TABLE "frontend_userprofile" ADD COLUMN "id" serial NOT NULL PRIMARY KEY;
The error was: multiple primary keys for table "frontend_userprofile" are not allowed

django.db.utils.DatabaseError: multiple primary keys for table "frontend_userprofile" are not allowed

我认为原因是在以前的迁移user_id中已设置为主键,现在它正试图添加id为主键。有什么帮助吗?

4

1 回答 1

1

据我所知,您不能拥有 NULL 主键。那会很糟糕。

我建议删除该迁移中显示 Null=True 的部分,然后重试。

于 2013-02-05T15:52:33.897 回答