Django - legacy db and problems with the id field

I am integrating a MySQL database from a php application into a new Django project. Inspectdb worked well, I just had to change a couple of fields to ForeignKeys, and now all the current read and edit data works fine.

The problem is that when I try to create a new record, I get an error message . Tracing starts with a call , and the exception comes from the MySQL cursor. In most cases, the column has a name , but in one case it is a named value: "Field 'id' doesn't have a default value"form.save()id

class ModelOne(models.Model): #normal "id" named pk 
    id = models.AutoField(primary_key=True, db_column='id', default=None)
    other_fields = ...

class ModelTwo(models.Model): #specific pk
    named_pk = models.AutoField(primary_key=True, db_column='named_pk',
                                default=None)
    other_fields = ...

For ModelTwo, when I have a POST valid form, I get an error, but if I return to my data list, a new element will appear! And after I checked the last values idin the shell, I see that they increase correctly.

But for ModelOne (only with id), the error still appears, and pk becomes 2147483647 (max) and the subsequent ones saved due to duplicate identifiers. (next highest pk is only 62158)

What do I need to do for these id fields to work correctly?


update: Still cannot fix it. Thinking about dumping data and importing it into new Django-built tables. Still looking for a solution to this problem.


Update2: db shell information

ModelOne:

+-------------+--------------+-------+------+---------+-----------------+
| Field       | Type         | Null  | Key  | Default | Extra           |
| id          | int(11)      | NO    | PRI  | NULL    | auto_increment  |

ModelTwo:

+-------------+--------------+-------+------+---------+-----------------+
| Field       | Type         | Null  | Key  | Default | Extra           |
| named_pk    | int(11)      | NO    | PRI  | NULL    | auto_increment  |
+5
3

db, /.

, , , SQL pk.

, .

+1

. (/), , , .

, .

auth_user MySQL :

ALTER TABLE auth_user MODIFY `id` INT(11) NOT NULL AUTO_INCREMENT;

:

http://webit.ca/2012/01/field-id-doesnt-have-a-default-value/

+5

It makes sense to define pk for ModelTwo (as you already do), because your pk has a different name "named_pk". However, there is no need to explicitly define "id" as your pk for ModelOne. By default, Django will create an identity column. Therefore, do not define an id column at all for ModelOne.

UPDATE: remove "default = None" from the model and default NULL from the database for ModelTwo for named_pk

+3
source

All Articles