It took me a little searching to learn how to do this. Unlike most migrations, django can't generate name changes automatically.
StackOverflow has a recipe for changing the name of a model and a couple of fields:
http://stackoverflow.com/questions/25091130/django-migration-strategy-for-renaming-a-model-and-relationship-fields
I simplified that recipe for the case when you only want to change a single field name:
https://gist.github.com/dhbradshaw/e2bdeb502b0d0d2acced
Recursive algorithms can be slow because they end up solving the same little problems over and over again. To speed them up, you can use a technique called "memoization." Memoization allows algorithms go much more quickly by remembering solutions to problems they have already solved. I’m the recursive algorithm. This blog is my memoization.
Showing posts with label migrations. Show all posts
Showing posts with label migrations. Show all posts
Tuesday, November 18, 2014
Changing fieldnames with django 1.7
Labels:
change field name,
django 1.7,
migrate,
migrations
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:
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 makemigrationsand then run./manage.py migrateand the new field will be added to your db. To avoid dealing with errors for your existing models however, you can use the--fake:
- Initialize migrations for your existing models:
./manage.py makemigrations myapp- Fake migrations for existing models:
./manage.py migrate --fake myapp- 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- Run makemigrations again (this will add a new migration file in migrations folder that add the newfield to db):
./manage.py makemigrations myapp- Run migrate again:
./manage.py migrate myapp
Subscribe to:
Posts (Atom)