6

What is the best solution if I want to upgrade (alter) my database schema (add new fields to tables by adding them just to Django models) without losing data in these tables? "syncdb" not adding them of course, so I need your advices how to alter tables without deleting them and recreating again with syncdb.

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Ignas Butėnas
  • 6,061
  • 5
  • 32
  • 47

3 Answers3

10

When south isn't an option I just manually write scripts for small changes. and big ones i use

./manage.py dumpdata appname

http://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-appname-appname-appname-model

Throw that into a file. Run a regex replace to update any added /removed fields and then a reset of that app is possible. I have to admit i haven't done this in a while but i can get some specific code to do this for you if needed.

it loads back up with loaddata

edit

Django dump data for a single model? This Question is similar and might have the info i was talking about.

Still let me know if you need and i'll dig up my old script (or write out a nice simple one) for you.

UPDATE

./manage.py dumpdata appname --indent=4 > appname.json

#open your fav text editor and do a find/replace 

./manage.py reset appname
./manage.py loaddata appname.json

That should do it. When you do a find replace you only need to remove fields that you don't have any more and add fields that aren't nullable. (as a minimum).

Notes: the --indent=4 nicely formats everything for you. It means 4 spaces. the ./manage.py reset only works in pre django 1.3 (gah!) in django 1.3 you will have to do a ./manage dbshell and drop table. The sql for that is found from command ./manage.py sqlreset appname.

Community
  • 1
  • 1
James Khoury
  • 21,330
  • 4
  • 34
  • 65
  • Need to try and play with it to get familiar, but sounds reasonable. Of course if you have the script you mentioned and can share, it will be nice to look at it before writing my own :) But definitely will try to play with it, thanks! – Ignas Butėnas Apr 21 '11 at 06:14
  • I'm assuming you are running linux? – James Khoury Apr 21 '11 at 06:15
  • Mac!... oh noes! ;) i can't find my script but i can approximate the steps read my update. – James Khoury Apr 21 '11 at 06:48
  • This works easy and for the moment I will use this way. Later maybe will try south, but for now this should be enough :) – Ignas Butėnas Apr 22 '11 at 10:03
6

Learning curve...

http://south.aeracode.org/

South was merged into django core at version 1.7.
There is now a native django feature for data migration on schema changes.

John Mee
  • 50,179
  • 34
  • 152
  • 186
1

Django 1.7 has built-in migrations support.

See https://docs.djangoproject.com/en/dev/releases/1.7/#schema-migrations

user193130
  • 8,009
  • 4
  • 36
  • 64