Adding a field to a model

0 views
Skip to first unread message

Mark Engelberg

unread,
Mar 24, 2007, 9:04:28 PM3/24/07
to django...@googlegroups.com
I know that, unfortunately, there's no painless way to migrate all the
data in your database when you add a new optional field to your model.
Pity.

So what is the MOST painless way to do this?

--Mark

John M

unread,
Mar 24, 2007, 9:08:17 PM3/24/07
to Django users
I think the new .96 version has a export / import data function now.

Malcolm Tredinnick

unread,
Mar 24, 2007, 9:19:46 PM3/24/07
to django...@googlegroups.com

(1) Add the field to your model.

(2) Run "manage.py sql <app_name>" and note the type of column that is
added to the model's table.

(3) At your database prompt ("manage.py shell" and go from there),
execute "ALTER TABLE ADD COLUMN ... DEFAULT ...", filling in the first
"..." part with the column definition you noted before. You will also
need to add a DEFAULT value to the column at the database level so that
existing entries have a value for that column. If the column can be
NULL, you won't need the default value -- it will just put NULLs in
there for all the existing entries.

(4) Sit back with drink of choice and realise just how painless the
whole process was.

Regards,
Malcolm


James Bennett

unread,
Mar 24, 2007, 9:55:43 PM3/24/07
to django...@googlegroups.com
On 3/24/07, Malcolm Tredinnick <mal...@pointy-stick.com> wrote:
> (3) At your database prompt ("manage.py shell" and go from there),
> execute "ALTER TABLE ADD COLUMN ... DEFAULT ...", filling in the first
> "..." part with the column definition you noted before. You will also
> need to add a DEFAULT value to the column at the database level so that
> existing entries have a value for that column. If the column can be
> NULL, you won't need the default value -- it will just put NULLs in
> there for all the existing entries.

Alternative, and even better in my experience: write a SQL file which
will run the update inside a transaction, and commit that into the SVN
repo with your app so you have a history of what you've done to the
DB.

--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."

Reply all
Reply to author
Forward
0 new messages