Friday, December 28, 2018

Re: MySQL accepts 0 for a primary key but Django does not

Hello Derek,

There's no setting but this is controlled by the allows_auto_pk_0 feature flag [0].
Database feature are set to the default database configurations so Django can
minimized the number of introspection queries required to work appropriately
each time a connection is opened.

In order to override it I suggest you create a subclass of django.db.backends.mysql.base.DatabaseWrapper in
a custom foo.bar.base module and set feature_class to a .features.DatabaseFeatures[1]
subclass that sets the allows_auto_pk_0 flag to True.

e.g.

#foo/bar/base.py

from django.db.backends.mysql.base import DatabaseWrapper as BaseDatabaseWrapper
from django.db.backends.mysql.features import DatabaseFeatures as BaseDatabaseFeatures

class DatabaseFeatures(BaseDatabaseFeatures):
    allows_auto_pk_0 = True

class DatabaseWrapper(BaseDatabaseWrapper):
    features_class = DatabaseFeatures

Then you'll want to point your DATABASES.ENGINE to 'foo.bar' instead of 'django.db.backends.mysql'.

Keep in mind that Django expects

1. A .base submodule [2]
2. A class named DatabaseWrapper [3]

The foo.bar module path can be renamed to whatever you want.

Cheers,

[0] https://github.com/django/django/blob/e817ae74da0e515db31907ebcb2d00bcf7c3f5bc/django/db/backends/mysql/features.py#L27
[1] https://github.com/django/django/blob/e817ae74da0e515db31907ebcb2d00bcf7c3f5bc/django/db/backends/mysql/base.py#L184
[2] https://github.com/django/django/blob/e817ae74da0e515db31907ebcb2d00bcf7c3f5bc/django/db/utils.py#L110
[3] https://github.com/django/django/blob/e817ae74da0e515db31907ebcb2d00bcf7c3f5bc/django/db/utils.py#L203

Le vendredi 28 décembre 2018 07:47:31 UTC-5, Derek a écrit :
I am working with some legacy data and need to preserve the existing record ID's which, in some tables, include the value of 0 for their auto-increment field.

I have updated the configuration file for MySQL such that the sql_mode is set to include 'NO_AUTO_VALUE_ON_ZERO'.  

I can check that this works by running the following test inside the MySQL shell:

create table number (number int not null auto_increment primary key); insert into number(number) values (0); select * from number; drop table number;

+--------+
| number |
+--------+
|      0 |
+--------+
1 row in set (0,00 sec)

However, when I try this approach with one of my existing models (in the Django shell) I get an error:

from myapp.models import MyModel
MyModel.objects.create(pk=0, direction=1, code='UNK')

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/manager.py", line 157, in create
    return self.get_queryset().create(**kwargs)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/query.py", line 322, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/base.py", line 545, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/base.py", line 573, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/base.py", line 654, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/base.py", line 687, in _do_insert
    using=using, raw=raw)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/manager.py", line 232, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/query.py", line 1514, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 902, in execute_sql
    for sql, params in self.as_sql():
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 860, in as_sql
    for obj in self.query.objs
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 350, in get_db_prep_save
    prepared=False)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 607, in get_db_prep_value
    value = connection.ops.validate_autopk_value(value)
  File "/home/gamesbook/,virtualenvs/proj/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 336, in validate_autopk_value
    raise ValueError('The database backend does not accept 0 as a '
ValueError: The database backend does not accept 0 as a value for AutoField.

Is there a setting I need to change such that Django does not raise this error and allows the PK to be zero?

Thanks
Derek

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ef9a6e9c-29bf-4435-a6ad-13ae53c41578%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment