Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a model in Django gives me "Warning: Field 'id' doesn't have a default value"

I have a very basic 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'

Because I did not specify the PK, Django took care of that for me. I see the field in my database which is called "id", marked as a primary key and auto-increment. I find odd to be getting that warning since everything is cool on the DB and model end. The error is:

_mysql_exceptions.Warning

Warning: Field 'id' doesn't have a default value

My work around when saving is to set the id to 0. It kills the warning and the id gets set properly anyway since MySQL handles it.

case = Case()
case.id = 0 #ugly workaround for - Warning: Field 'id' doesn't have a default value
case.name = request.POST[u'case[name]']
case.save()

The issue with this solution is:

  1. It's ugly
  2. The new PK is inaccessible after saving which makes it impossible to serialize properly

Does anyone know how to fix this?

I'm running:

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 create 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
like image 834
Tony Avatar asked Nov 10 '11 00:11

Tony


People also ask

Does Django automatically create ID?

An id field is added automatically, but this behavior can be overridden. See Automatic primary key fields. The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it's worth noting Django uses SQL tailored to the database backend specified in your settings file.

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is default auto field in Django?

Starting new projects in Django 3.2, the default type for primary keys is set to a BigAutoField which is a 64 bit integer.

What is the difference between ID and PK in Django?

pk is the attribute that contains the value of the primary key for the model. id is the name of the field created as a primary key by default if none is explicitly specified.


1 Answers

I'd like to expand on this question as I've ran into it this week. I was getting this same exact error and taking a look at the model definition and SQL definition showed that:

  1. The models affected either had no PK explicitly defined or had a PK explicitly defined (both had problems). This alone seemed unrelated.

  2. The tables affected had the "id" definition as in the OP, i.e. id int(11) NOT NULL AUTO_INCREMENT. The PRIMARY KEY is set as expected.

  3. Looking into the MySQL query log I got something to this extent:

    INSERT INTO `x` (...) VALUES (...)
    SHOW WARNINGS
    ROLLBACK
    

    Running the query individually is successful, and SHOW WARNINGS reflects the warning noted in the OP.

I however came across a MySQL-end fix, http://webit.ca/2012/01/field-id-doesnt-have-a-default-value/ mentioned that resetting the id definition (which at a cursory glance appears to not be any different) fixes the problem. I can't explain why this works, but it addresses the problem without any additional code changes. I believe this may be in some way linked to removing records, but the whole issue seems non-sensical to me.

like image 191
Aea Avatar answered Oct 13 '22 01:10

Aea