south migration: "database backend does not accept 0 as a value for AutoField" (mysql) south migration: "database backend does not accept 0 as a value for AutoField" (mysql) python python

south migration: "database backend does not accept 0 as a value for AutoField" (mysql)


If this happens when you run manage.py migrate (or manage.py syncdb in old versions), the reason maybe is that you have tried to add a foreign key to a model which uses AutoField as its primary key, and use 0 as the default value. Edit the migration file and remove the argument default=0 in AddField operations. It works for me in Django 1.10.


I wasn't using South, but I recently upgraded from Django 1.4 to 1.6 (with MySQL as db backend for both), and was getting the same ValueError when trying to save some models. I tracked it down to a field that was a recursive ForeignKey. So I had:

class Foo(models.Model):    ...    duplicate = models.ForeignKey('self', blank=True, null=True)    ...

Somewhere along the line—unfortunately I'm not sure where—many of my objects had gotten the value of 0 for duplicate_id.

>>> Foo.objects.filter(duplicate_id=0).count()2078

This didn't occur for any of my other ForeignKey fields, only the self-referential one. So I set the values of that field back to None, and this fixed the error.

>>> Foo.objects.filter(duplicate_id=0).update(duplicate=None)2078L

Because this particular error doesn't point you to a specific field that's causing problems, in general you can check if a ForeignKey field fieldname has any 0 values:

>>> Foo.objects.filter(fieldname_id=0).count()

If this gives a non-zero result, that field probably needs to be fixed.


A long-long time ago there was a problem with Autofield.

https://code.djangoproject.com/ticket/17653

an interesting quotes:

A:

It seems you are trying to save 0 to a ForeignKey which points to an AutoField. But, this is illegal, as the AutoField will not accept that value and so the ForeignKey can not hold that value either.

B:

So this fix creates another problem when you need to be able to accept a value of 0 (or if you are working on a DB that already has a value of 0!) in an autofield. In my case, I need to accept an ID of zero so that my foreign key can point to zero so that a unique constraint can work properly.

It looks like you have 0 in "user"."user_id".
But again... Full StackTrace, please...