views:

1950

answers:

3

Hi

I have a little website with a few users and I'd like to add a field to one of my models (and hence tables.) The problem is that syncdb of course won't touch the existing models and I'm trying to figure out how to add this field to the model/table without having to repopulate the entire thing.

Example:

class Newspaper(models.Model):
    name = models.CharField()

class UserProfile(models.Model):
    user = models.ForeignKey(user, unique=True)
    reads = models.ManyToManyField(Newspaper)

Now I'd like to add a URL field (blank=True) to the Newspaper model without breaking the user profiles.

Any ideas?

+2  A: 

You could try getting the SQL for your new field using:

manage.py sql appname

Where appname is the name of the application in which your newspaper class lives.

Then, you could manually add a field to your appname_newspaper table, using ALTER TABLE. I'm not aware of a way to do this directly with Django, since Django does not support migrations.

Dominic Rodger
+9  A: 

There's no built-in way to do this. However there are a number of third-party projects that will do it for you. The two leading ones are called South and django-evolution, although there are various others as well (including one I've been involved with, dmigrations).

I would definitely recommend South - it has a number of really neat features and works really well.

Daniel Roseman
+1  A: 

Just to reiterate using South - it's undergoing continuous development (which sometimes the documentation doesn't keep quite up with), but is very very useful.

I used it to migrate a legacy database (one table) across into several Django models (with ForeignKey, ManyToMany fields and others) and it helped immeasurably. I split the migrations into areas such as 'adding a field', 'adding a model', 'populating the manytomany lookup table', 'populating the foreign key fields' etc.

You can use python code in the migrations, which helps with the inevitable teasing of data from one format into the other (eg text representations of date and time - ugh, into DateTime database fields).

Highly recommended.

tonemcd