Home » Odeon Blogs » Stefan Talpalaru, CTO »

adding a NOT NULL column with South

adding a NOT NULL column with South

When using South to add a NOT NULL column to an existing Django model with some rows already in the database, you'll get an error like "django.db.utils.IntegrityError: column "newcolumn" contains null values". It's very confusing, because this is a new column, how can it have null values in it? Let's look at the SQL query executed:

  1. ALTER TABLE "myapp_mymodel" ADD COLUMN "newcolumn" text NOT NULL;

Looks OK. Nothing suspicious in it. Time to read the postgresql docs? Well, it seems that when a column is added and no default value is specified, the db server does the fastest update of the existing rows by setting the value to NULL. This, of course, conflicts with the NOT NULL requirement in the ALTER statement with the corresponding error message. Now that we know the mechanism, the solution is simple: set a default in the field's definition:

  1. newcolumn = models.TextField(blank=True, default='')


Discussion

  1. this is not confusing, what values did you expect to have? uninitialized garbage a la C?

    also you should create the column allowing null values, set the values for your newly created col on all the existing rows and then set the not null; you're changing the meaning of your model by setting a default and now you won't get an error when you omit that field.


  2. I am avoiding NULL columns because they involve increased complexity at the database server level and lowered performance. Here's an interesting post and comment thread about it: http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/




Leave a Comment :

(required)


(required)




(required)




(required)






Leave a Comment


Page generated in: 0.50s