deltanovember
deltanovember

Reputation: 44041

Why does Django throw a 'does not exist' error when I try to add a field

Currently I'm using the default admin portal which is working fine. Then inside models.py I try to add a field as follows:

class MyModel(models.Model):
    # new field is 'info'
    info = models.CharField(max_length=100)

MyModel has already been successfully defined and used in the above code I simply wish to add a single field. I rerun sync

python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

However then Django throws an error when I try to use the interface

column myproject_mymodel.info does not exist

What am I doing wrong?

Upvotes: 0

Views: 435

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208405

manage.py syncdb will only create tables that do not exist, it will not work for adding or removing columns, or for modifications to columns.

I suggest reading through the following chapter of the Django Book (which is free online):
Chapter 10: Advanced Models

Here are the steps given in that chapter for adding fields:

First, take these steps in the development environment (i.e., not on the production server):

  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.
  4. Launch the Python interactive shell with manage.py shell and verify that the new field was added properly by importing the model and selecting from the table (e.g., MyModel.objects.all()[:5]). If you updated the database correctly, the statement should work without errors.

Then on the production server perform these steps:

  1. Start your database’s interactive shell.
  2. Execute the ALTER TABLE statement you used in step 3 of the development environment steps.
  3. Add the field to your model. If you’re using source-code revision control and you checked in your change in development environment step 1, now is the time to update the code (e.g., svn update, with Subversion) on the production server.
  4. Restart the Web server for the code changes to take effect.

Upvotes: 3

Related Questions