Jul 4, 2011

Making Changes to a Database Schema

Adding Fields

  1. Add the field to your model.
  2. Run manage.py sqlall [yourapp] to see the new CREATE TABLE statement for the model. Note the column definition for the new field.
  3. Start your database’s interactive shell (e.g., psql or mysql, or you can use manage.py dbshell). Execute an ALTER TABLE statement that adds your new column.

Adding NOT NULL Columns

BEGIN;
ALTER TABLE books_book ADD COLUMN num_pages integer;
UPDATE books_book SET num_pages=0;
ALTER TABLE books_book ALTER COLUMN num_pages SET NOT NULL;
COMMIT;

Removing Fields

  1. Remove the field’s code from your model class and restart the Web server.
  2. Remove the column from your database, using a command like this: 
    ALTER TABLE books_book DROP COLUMN num_pages;
Removing Many-to-Many Fields
  1. Remove the ManyToManyField code from your model class and restart the Web server.
  2. Remove the many-to-many table from your database, using a command like this:
    DROP TABLE books_book_authors;

Using South ;)

South brings migrations to Django applications. Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications. 

No comments: