且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中保存模型会给我& quot;警告:字段' id'没有默认值"

更新时间:2022-12-05 12:43:50

我想在本周遇到的这个问题上进行扩展.我遇到了同样的确切错误,并查看了模型定义和SQL定义,结果表明:

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. 受影响的模型要么未明确定义PK,要么已明确定义PK(均存在问题).仅此一项似乎无关.

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

受影响的表具有与OP中相同的"id"定义,即 id int(11)NOT NULL AUTO_INCREMENT . PRIMARY KEY 已设置为预期值.

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.

在MySQL查询日志中,我得到了某种程度的帮助:

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

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

单独运行查询成功,并且 SHOW WARNINGS 反映了OP中记录的警告.

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

但是我遇到了一个MySQL端修复程序, http://webit.ca/2012/01/field-id-doesnt-have-a-default-value/提到重置ID定义(粗略地看似乎没有什么不同)可以解决此问题.我无法解释为什么会这样,但是无需任何其他代码更改即可解决该问题.我认为这可能与删除记录有关,但是整个问题对我来说似乎是无意义的.

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.