I’ve been working on a sqlite3 database with a Django project. I’m moving the project to the production environment where I use Postgres. I’ve used South, so I have all my migrations automated.
I’m running into the following error while trying to migrate the schema:
[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"
This is the relevant part of the migration file:
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'})
}
And of the model:
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True, unique=True)
company = models.ForeignKey(Company, null=True, default=None)
EDIT
As suggested by Jordan, you can’t have both a null primary key, so the following changes solve this problem:
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)
But I still have a problem finishing the migration:
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
I think the reason is that in a previous migration user_id has been set to primary key and now it’s trying to add id as primary key. Any help with this?
You can’t have a NULL primary key, as far as i know. That would be bad.
I recommend removing the part that says Null=True in that migration and trying again.