Django not setting default column value in MySQL
Posted by Kelvin on 07 Jun 2010 at 06:42 pm | Tagged as: programming
Django 1.1 refuses to set the default value of columns when creating SQL.
For example, given this model,
class Test(models.Model): price = models.IntegerField(default=0)
Django generates the following SQL:
CREATE TABLE `test` ( `id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `price` INTEGER NOT NULL ) ;
Its a relatively easy fix:
1. Hunt down the django installation directory. On debian, using the python egg installation method, django is located /usr/lib/python2.5/site-packages/Django-1.1-py2.5.egg/django
2. Open db/backends/creation.py in a text editor.
3. Search for 'def sql_create_model'
4. Scroll down abit, and you should see the following block of code:
if f.primary_key: field_output.append(style.SQL_KEYWORD('PRIMARY KEY')) elif f.unique: field_output.append(style.SQL_KEYWORD('UNIQUE'))
BELOW it, add this:
if(f.default != models.fields.NOT_PROVIDED): field_output.append(style.SQL_KEYWORD('DEFAULT ' + f.default.__str__()))
5. Save and you're done!
The SQL now generated looks like this:
CREATE TABLE `test` ( `id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `price` INTEGER NOT NULL DEFAULT 0 ) ;