Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering database tables in Django

I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using syncdb to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the documentation:

Syncdb will not alter existing tables

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

It seems that altering existing tables will have to be done "by hand".

What I would like to know is the best way to do this. Two solutions come to mind:

  • As the documentation suggests, make the changes manually in the DB;
  • Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big)

Any ideas?

like image 946
Farinha Avatar asked Aug 30 '08 14:08

Farinha


People also ask

Can you alter a table with data in it?

Existing tables can be altered with an ALTER TABLE statement. An ALTER TABLE statement is part of DDL, and is for altering a table schema only; we'll look at updating data in a table later in this book.

How delete all data from table in Django?

If you want to remove all the data from all your tables, you might want to try the command python manage.py flush . This will delete all of the data in your tables, but the tables themselves will still exist.


1 Answers

Manually doing the SQL changes and dump/reload are both options, but you may also want to check out some of the schema-evolution packages for Django. The most mature options are django-evolution and South.

EDIT: And hey, here comes dmigrations.

UPDATE: Since this answer was originally written, django-evolution and dmigrations have both ceased active development and South has become the de-facto standard for schema migration in Django. Parts of South may even be integrated into Django within the next release or two.

UPDATE: A schema-migrations framework based on South (and authored by Andrew Godwin, author of South) is included in Django 1.7+.

like image 174
Carl Meyer Avatar answered Oct 14 '22 18:10

Carl Meyer