Tuesday, August 25, 2015

Re: Django 1.7 migrations: Adding one field to User`s model

 
On Tue, Aug 25, 2015, at 08:51, marcin.j.nowak@gmail.com wrote:
Hi,
 
I would like to add one field to User.
 
I've created new model based on original Django`s user:
 
 class User(AbstractUser):
    is_verified = models.BooleanField(default=False)
 
    class Meta:
        db_table = 'auth_user'
 
 
Now I'm trying to make migrations, but Django tries to create `auth_user` table from scratch, and this is not what I'm expecting.
 
I've tried to migrate schema by adding one field:
 
[...] 
     operations = [
        migrations.AddField('User', 'is_verified', models.BooleanField(default=False)),
    ]
 
But during migrations Django dies at:
 
[...]
  File "eggs/Django-1.7.8-py2.7.egg/django/db/migrations/migration.py", line 76, in mutate_state
    operation.state_forwards(self.app_label, new_state)
  File "eggs/Django-1.7.8-py2.7.egg/django/db/migrations/operations/fields.py", line 26, in state_forwards
    state.models[app_label, self.model_name.lower()].fields.append((self.name, field))
KeyError: ('myapp', u'user')
 
 
I need to add just one column using builtin migrations. 
How to do that?
This is bug or feature?
 
BR,
Marcin
 
Here's how I'd get around this (I've recently worked on a project with an existing db where we needed to track new changes via migrations, and this is what we did).
 
I'm assuming your project has no existing migrations. If it does, it should not include migrations for this specific model. If it does, you've another problem.
 
1. Create an initial migrations with the model that matches the existing database.
2. Add any new fields, etc.
3. Create new migrations that apply changes.
4. Run python manage.py migrate --fake-initial. This will skip the *first* migrations for tables that exist, and proceed with other ones. Since the first migration would have created a table that looks like your existing one, that's not an issue. The following migrations will add a field
 
Lemme know if this helps.
 
--
Hugo Osvaldo Barrera
 

No comments:

Post a Comment