Tuesday, November 18, 2014

database migrations in django 1.7+

http://stackoverflow.com/questions/24311993/how-to-add-a-new-field-to-a-model-with-new-django-migrations

I found migrations a bit sticky in a couple of my applications because I didn't initialize migrations right off.  Anyway, this link has a nice set of instructions that includes the case where you didn't start off initialized.

From the link:

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your db. To avoid dealing with errors for your existing models however, you can use the --fake:
  1. Initialize migrations for your existing models:
    ./manage.py makemigrations myapp
  2. Fake migrations for existing models:
    ./manage.py migrate --fake myapp
  3. Add the new field to myapp.models:
    from django.db import models
    
    class MyModel(models.Model):
    ... #existing fields
    newfield = models.CharField(max_length=100) #new field
  4. Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):
    ./manage.py makemigrations myapp
  5. Run migrate again:
    ./manage.py migrate myapp

No comments:

Post a Comment