I have a very simple model in Django:
class Case(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def save(self): if self.created_at == None: self.created_at = datetime.now() self.updated_at = datetime.now() super(Case, self).save() class Meta: db_table = u'cases'
Since I did not specify a PC, Django took care of this for me. I see a field in my database called "id" that is marked as primary key and auto-increment. I find it strange that I get this warning, because everything is fine over the database and the end of the model. Error:
_mysql_exceptions.Warning Warning: Field 'id' doesn't have a default value
My job when saving is to set id to 0. It kills the warning, and the identifier is set correctly, since MySQL handles it.
case = Case() case.id = 0
The problem with this solution is:
- It's not beautiful
- The new PK is not available after saving, which makes it impossible to serialize correctly
Does anyone know how to fix this?
I run:
Python 2.7.2 django.VERSION (1, 3, 1, 'final', 0) mysql Ver 14.14 Distrib 5.1.45, for apple-darwin10.2.0 (i386) using readline 5.1 MySQL_python-1.2.3-py2.7-macosx-10.4-x86_64.egg
And my creation table looks like this:
CREATE TABLE `cases` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=45 DEFAULT CHARSET=latin1